7ms Java solution


  • 0
    B
        public int[] findDiagonalOrder(int[][] matrix) {
            boolean direction = true;
            int r, c;
            r = c = 0;
            int rows = matrix.length;
            if(rows==0) return new int[0];
            int cols = matrix[0].length;
            int[] result = new int[rows*cols];
            int count = 0;
            while(count<result.length-1){
                while(direction){
                    if(r>0&&c<cols-1){
                        result[count++] = matrix[r--][c++];
                    }else if(r==0&&c<cols-1){
                        direction = false;
                        result[count++] = matrix[r][c++];
                    }else{
                        direction = false;
                        result[count++] = matrix[r++][c];
                    }
                }
                while(!direction){
                    if(r<rows-1&&c>0){
                        result[count++] = matrix[r++][c--];
                    }else if(r<rows-1&&c==0){
                        direction = true;
                        result[count++] = matrix[r++][c];
                    }else{
                        direction = true;
                        result[count++] = matrix[r][c++];
                    }
                }
            }
            if(count==result.length-1)  result[count] = matrix[rows-1][cols-1];
            return result;
        }
    }```

Log in to reply
 

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