LeetCode 498 Diagonal Traverse (Python)

Posted by 小明MaxMing on November 1, 2024

题目

Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order.

解题思路

i+j相同的数在一组,偶数翻转

代码

class Solution:
    def findDiagonalOrder(self, matrix: List[List[int]]) -> List[int]:
        m = len(matrix)
        n = len(matrix[0])
        dic = defaultdict(list)
        for i in range(m):
            for j in range(n):
                dic[(i + j)].append(matrix[i][j])
        res = []
        for i in range(m + n - 1):
            if i % 2:
                res.extend(dic[i])
            else:
                res.extend(dic[i][::-1])
        return res

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅