Diagonal traverse

题目链接:https://leetcode.com/contest/...

就是找index的规律。。

public class Solution {
    public int[] findDiagonalOrder(int[][] matrix) {
        if(matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) return new int[0];
        
        int m = matrix.length, n = matrix[0].length;
        int[] result = new int[m*n];
        int i = 0;
        for(int count = 0; count <= m + n; count++) {
            if(count % 2 == 0) {
                for(int j = Math.max(0, count - m + 1); j <= Math.min(count, n - 1); j++) {
                    result[i++] = matrix[count - j][j];
                }
            }
            else {
                for(int j = Math.max(0, count - n + 1); j <= Math.min(count, m - 1); j++) {
                    result[i++] = matrix[j][count - j];
                }
            }
        }
        
        return result;
    }
}

lulouch13
13 声望6 粉丝