Leetcode 498. Diagonal Traverse

2021-07-27 15:49:46 浏览数 (1)

文章作者:Tyan 博客:noahsnail.com | CSDN | 简书

1. Description

2. Solution

**解析:**Version 1,根据矩阵对角线的规律,对角线的数量为m n-1,对角线的起点(左下到右上)为第一列加上最后一行的数据,顺序为行数一次加1,列不变,到左下角后,行数不变,列数依次加1,对角线上的数据依次为行减1,列加1。由于是对角线遍历是连续的,因此,行数加列数的和为奇数时,需要反转对角线数据。

  • Version 1
代码语言:javascript复制
class Solution:
    def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]:
        m = len(mat)
        n = len(mat[0])
        result = []
        i = -1
        j = 0
        for _ in range(m n-1):
            if i != m -1:
                i  = 1
            else:
                j  = 1
            current_row = i
            current_column = j
            temp = []
            while current_row > -1 and current_column < n:
                temp.append(mat[current_row][current_column])
                current_row -= 1
                current_column  = 1
            if (i   j) % 2 == 1:
                result  = temp[::-1]
            else:
                result  = temp
        return result

Reference

  1. https://leetcode.com/problems/diagonal-traverse/

0 人点赞