Intuitive Solution (JAVA)


  • 0
    N
    class Solution {
        public int[] findDiagonalOrder(int[][] matrix) {
            
            int row=matrix.length;
              if(matrix==null || row==0 || matrix[0].length==0)
                  return new int[0];
            int col=matrix[0].length;
            
            int[] arr= new int[row*col];
            int k=0;
            int i=0,j=0;
          
            while(i<row || j<col)
            {
                while(i>=0 && j<col)
                {
                    arr[k++]=matrix[i][j];
                    if(j<col-1)
                    {
                        i--;
                        j++;
                    }
                    else
                        break;
                }
                
                i++;
                
                while(i<row && j>=0)
                {
                    arr[k++]=matrix[i][j];
                    if(i<row-1)
                    {
                        i++;
                        j--;
                    }
                    else
                        break;
                }
                j++;
            }
            
            return arr;
            
        }
    }
    

Log in to reply
 

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