Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

search in row and column sorted matrix leetcode

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if(matrix.length == 0) return false;
        int rows = matrix.length;
        int cols = matrix[0].length;
        
        int left = 0;
        int right = rows*cols-1;
        
        while(left <= right){
            int mid = left + (right-left)/2;
            int midElement = matrix[mid/cols][mid%cols];
            if(midElement == target) return true;
            if(midElement < target) left = mid+1;
            else right = mid-1;
        }
        return false;
    }
}
 
PREVIOUS NEXT
Tagged: #search #row #column #sorted #matrix #leetcode
ADD COMMENT
Topic
Name
7+4 =