Java Solution with explanation


  • 0
    L

    Inspired from https://discuss.leetcode.com/topic/77922/java-solution-easy-to-understand-o-n-7ms/2. I liked the simplicity of that solution.

        public int[] findDiagonalOrder(int[][] matrix) {
            int rows = matrix.length;
            if(rows==0) {
                return new int[0];
            }
                    
            int cols = matrix[0].length;
            //r+c=sum all the times.
            List<Integer> list = new ArrayList<>();
            byte b = 1;//can toggle for odd/even.
            int r=0,c=0;
            for(int sum=0;sum<=rows+cols-2;sum++) {
                if(b==1) {
                    //we go up diagonally.
                    r = Math.min(sum,rows-1);    
                    c = sum-r;
                    while(r>=0 && c<=cols-1) {
                        list.add(matrix[r--][c++]);
                    }
                }
                else {
                    //we come down diagonally.
                    c = Math.min(sum,cols-1);
                    r = sum-c;
                    while(r<=rows-1 && c >=0) {
                        list.add(matrix[r++][c--]);
                    }
                }
                
                b ^=1;//toggle the switch.
            }
            return list.stream().mapToInt(i->i).toArray();
        }
    

Log in to reply
 

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