498. Diagonal Traverse对角线z型traverse

[抄题]:

Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image.

Example:

Input:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
Output:  [1,2,4,7,5,3,6,8,9]
Explanation:

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

不知道怎么控制方向:由于每次只走一格,所以用xy+-d即可,d=1

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[一句话思路]:

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. 为了保证第一个数一样,都是先直接添加后再处理 

result[i] = matrix[row][col];
row -= d;
col += d;

[二刷]:

  1. 为了避免处理>边界时顺便把<边界处理了,<边界的小情况要写在后面

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

换方向用d = -d来控制

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[算法思想:迭代/递归/分治/贪心]:

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

 [是否头一次写此类driver funcion的代码] :

 [潜台词] :

public class Solution {
    public int[] findDiagonalOrder(int[][] matrix) {
        if (matrix == null || matrix.length == 0) return new int[0];
        int m = matrix.length, n = matrix[0].length;
        
        int[] result = new int[m * n];
        int row = 0, col = 0, d = 1;
        
        //for loop: add to result, expand, handle corner cases
        for (int i = 0; i < m * n; i++) {
            result[i] = matrix[row][col];
            
            row -= d;
            col += d;
            
            if (row >= m) {row = m - 1; col += 2; d = -d;}
            if (col >= n) {col = n - 1; row += 2; d = -d;}
            if (row < 0) {row = 0; d = -d;}
            if (col < 0) {col = 0; d = -d;}
        }
        
        return result;
    }
}
View Code
原文地址:https://www.cnblogs.com/immiao0319/p/9462047.html