Java Solution - 6ms / beats 99.15%


  • 0
    S

    A focus on making code as readable as possible. Could probably reconstruct if-statements to improve code-motion.

    public int[] findDiagonalOrder(int[][] matrix) {
            if (matrix.length == 0) return new int[0];
            if (matrix.length == 1) return matrix[0];
            if (matrix[0].length == 0) return new int[0];
            
            int xBarrier = matrix[0].length - 1;
            int yBarrier = matrix.length - 1;
            
            int p = 0, pMax = matrix.length * matrix[0].length;
            int[] res = new int[pMax];
            
            int xIn = 0, yIn = 0;
            boolean goingUp = true;
            
            while (p < pMax) {
                res[p] = matrix[yIn][xIn];
                
                if (goingUp) {
                    if (yIn == 0 && xIn == xBarrier) { //top right
                        yIn++;
                        goingUp = false;
                    } else if (yIn == 0) { //top
                       goingUp = false;
                       xIn++;
                   } else if (xIn == xBarrier) { //right
                       goingUp = false;
                       yIn++;
                   } else {
                       yIn--;
                       xIn++;
                   }
                } else {
                   if (xIn == 0 && yIn == yBarrier) { //bottom left
                       xIn++;
                       goingUp = true;
                   } else if (xIn == 0) { // left
                       yIn++;
                       goingUp = true;
                   } else if (yIn == yBarrier) { //bottom
                       xIn++;
                       goingUp = true;
                   } else {
                       yIn++;
                       xIn--;
                   }
                }
                p++;
            }
            
            return res;
    

Log in to reply
 

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