Diagonal Traverse

matrix打印类典型问题,matrix划分为左上,右下两个部分。左上部分每个对角线以左下(i,0)为准,i<m; 右下部分每个对角线以左下(m-1,j)为起始,满足1<j<n. 一次AC

public class Solution {
    public int[] findDiagonalOrder(int[][] matrix) {
        if(matrix==null || matrix.length==0)
            return new int[0];
        int m = matrix.length; int n = matrix[0].length;
        int[] ans = new int[m*n];int idx = 0;

        for(int i=0;i<m;i++){
            ArrayList<Integer> tmp = new ArrayList<Integer>();
            int x = i; int y =0;
            while(x>=0&&y<n){
                if(i%2==0) tmp.add(matrix[x--][y++]);
                else tmp.add(0,matrix[x--][y++]);
            }
            for(int t:tmp) ans[idx++] = t;
        }

        for(int j=1;j<n;j++){
            ArrayList<Integer> tmp = new ArrayList<Integer>();
            int x = m-1; int y =j;
            while(x>=0&&y<n){
                if((x+y)%2==0) tmp.add(matrix[x--][y++]);
                else tmp.add(0,matrix[x--][y++]);
            }
            for(int t:tmp) ans[idx++] = t;
        }
        return ans;
    }
}
  • 超出上边界时,row<0, 此时 row=0, col不变,换方向

  • 超出左边界时,col<0, 此时col=0, row不变,换方向

  • 超出下边界时,row>=m, 此时row=m-1, col+=2, 换方向

  • 超出右边界时,col>=n, 此时col=n-1, row+=2, 换方向

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 = 0;
        int[][] dirs = {{-1, 1}, {1, -1}};

        for (int i = 0; i < m * n; i++) {
            result[i] = matrix[row][col];
            row += dirs[d][0];
            col += dirs[d][1];

            if (row >= m) { row = m - 1; col += 2; d = 1 - d;}
            if (col >= n) { col = n - 1; row += 2; d = 1 - d;}
            if (row < 0)  { row = 0; d = 1 - d;}
            if (col < 0)  { col = 0; d = 1 - d;}
        }

        return result;
    }
}

Reshape the Matrix

public int[][] matrixReshape(int[][] nums, int r, int c) {
    int n = nums.length, m = nums[0].length;
    if (r*c != n*m) return nums;
    int[][] res = new int[r][c];
    for (int i=0;i<r*c;i++) 
        res[i/c][i%c] = nums[i/m][i%m];
    return res;
}

results matching ""

    No results matching ""