Write an efficient algorithm that searches for a value in anmxnmatrix. This matrix has the following properties:
For example,
Consider the following matrix:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Giventarget=3
, returntrue
.
tag: binary search
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return false;
int n = matrix.length, m = matrix[0].length;
for (int i = 0; i < n; i++){
if (matrix[i][m - 1] < target) continue;
int left = 0, right = m - 1;
while (left + 1 < right){
int mid = left + (right- left) / 2;
if (matrix[i][mid] == target){
return true;
}
else if (matrix[i][mid] < target){
left = mid;
}
else{
right = mid;
}
}
if (matrix[i][right] == target) return true;
if (matrix[i][left] == target) return true;
}
return false;
}
}