Java Solution WITHOUT treating it as a SORTED LIST


  • 1
    private int[][] matrix;
    private int target;
    private int m;
    private int n;
    public boolean searchMatrix(int[][] matrix, int target) {
        
        this.target = target;
        this.matrix = matrix;
        m = matrix.length - 1;
        n = matrix[0].length - 1;
        
        return doSearchRow(0,m);
    }
    
    private boolean doSearchRow(int sm,int em){
        
        if(sm == em){
            return doSearchColumn(sm, 0,n);
        }
        
        int mm = (sm + em)/2;
        if(matrix[mm][n] == target) return true;
        else if(matrix[mm][n] > target) return doSearchRow(sm,mm);
        else return doSearchRow(mm + 1, em);
    }
    
    private boolean doSearchColumn(int m, int sn, int en){
        
        if(sn == en && matrix[m][sn] != target){
            return false;
        }
        int mn = (sn + en)/2;
        if(matrix[m][mn] == target) return true;
        else if(matrix[m][mn] > target) return doSearchColumn(m,sn,mn);
        else return doSearchColumn(m,mn + 1, en);
    }

Log in to reply
 

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