JAVA Easy Solution use two pointers


  • 0
    J
    public class Solution {
        public int[] findDiagonalOrder(int[][] matrix) {
            if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return new int[0];
            int row = matrix.length, col = matrix[0].length;
            int tag = 1,count = 0, i = 0, j = 0;
            int res[] = new int[row*col];
           
            while (i <= row - 1 && j <= col -1 && count < row*col) {
    
                    if (j == 0 || i == 0 || i == row - 1 || j == col - 1) {
                        if (count < row*col && i >= 0 && i <= row - 1 && j >= 0 && j <= col - 1) res[count] = matrix[i][j];
                        if (tag % 2 == 0) {
                            if (i < row - 1) i++;
                            else j++;
                        } else {
                            if (j < col - 1) j++;
                            else i++;
                        }
                        
                        tag++;
                        count++;
                    }
                    
                    if (tag % 2 == 0 && j > 0 && i < row - 1) {
                        res[count++] = matrix[i][j];
                        i++;
                        j--;
                    } else if (i > 0 && j < col - 1){
                        res[count++] = matrix[i][j];
                       i--;
                       j++;
                    }
                   
            }
            
            return res;
            
        }
    }

Log in to reply
 

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