9ms Java Solution


  • 0
    public class Solution {
        public int[] findDiagonalOrder(int[][] matrix) {
            if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
                return new int[0];
            }
            int rows = matrix.length;
            int cols = matrix[0].length;
            int[] res = new int[rows * cols];
            int index = 0, i = 0, j = 0;
            boolean goUp = true;
            while (index < res.length) {
                if (i >= 0 && i < rows && j >= 0 && j < cols) {
                    res[index++] = matrix[i][j];
                    i += goUp ? -1 : 1;
                    j += goUp ? 1 : -1;
                } else {
                    //Change direction;
                    if (goUp) {
                        i += (j == cols) ? 2 : 1;
                        j += (j == cols) ? -1 : 0;
                    } else {
                        j += (i == rows) ? 2 : 1;
                        i += (i == rows) ? -1 : 0;
                    }
                    goUp = !goUp;
                }
            }
            return res;
        }
    }
    

Log in to reply
 

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