74. Search a 2D Matrix
# Medium
Find possible row, then apply binary search
Consider edge case
// Some code
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int row = 0;
for(; row < matrix.length; row ++) {
int temp = matrix[row][0];
if(temp == target)
return true;
else if(temp > target)
break;
}
row = row == 0? 0: row - 1;
int left = 0, right = matrix[row].length - 1, temp;
while(left <= right) {
int mid = left + (right - left)/2;
temp = matrix[row][mid];
if(temp == target)
return true;
else if(temp < target)
left = mid + 1;
else
right = mid - 1;
}
return false;
}
}
Last updated
Was this helpful?