Java solution using staircase search


  • 0
    L

    Time complexity will be o(m+n).

     public boolean searchMatrix(int[][] matrix, int target) {
            if(matrix==null || matrix.length==0) {
                return false;
            }
            
            int row=0;
            int col=matrix[0].length-1;
            while(row<matrix.length&& row>=0 && col<matrix[0].length&& col>=0) {
                int val = matrix[row][col];
                if(val==target) {
                    return true;
                }
                else if(val>target) {
                    col=col-1;
                }
                else {
                    row = row+1;
                }
            }
            return false;
        }
    

Log in to reply
 

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