EASY UNDERSTAND SOLUTION(JAVA)


  • 0
    M

    when the raw+col is even, the orientation is from bottom left to the upper right,otherwise, the orientation is from the upper right to bottom left.Besides,the sum of raw+col is increase from 0 to raw-1+col-1 1by 1,so the breakthrough point the sum of raw+col

    public class Solution {
        public int[] findDiagonalOrder(int[][] matrix) {
            if(matrix.length==0||matrix[0].length==0)return new int[0];
            int raw=matrix.length;
            int col=matrix[0].length;
            int[] ret=new int[raw*col];
            int index=0;
            for(int rc=0;rc<raw+col-1;rc++){
                if((rc&1)==0){//the sum is even
                    int r=rc>=raw?raw-1:rc;
                    for(;r>=0&&rc-r<col;r--){
                        ret[index++]=matrix[r][rc-r];
                    }
                }else{//the sum is odd
                    int c=rc>=col?col-1:rc;
                    for(;c>=0&&rc-c<raw;c--){
                        ret[index++]=matrix[rc-c][c];
                    }
                }
            }
            return ret;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.