Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
- Integers in each row are sorted from left to right.
- The first integer of each row is greater than the last integer of the previous row.
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]Given target =
3, return true.-------------------------------------------------------------
Do 2 binary searches
Note that start <= end
Searching a 2D Sorted Matrix Part
class Solution {
public:
bool searchMatrix(vector<vector<int> > &matrix, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
// return false;
int m = matrix.size();
int n = matrix[0].size();
int start = 0, end = m-1;
if(target< matrix[0][0]) return false;
// binary search the first element of each row
while (start <= end) {
int mid = (start + end) / 2;
if (matrix[mid][0] == target) {
return true;
}
if (matrix[mid][0] > target) {
end = mid - 1;
}else {
start = mid + 1;
}
}
// binary search in that particular row
int row = end;
start = 0;
end = n-1;
while (start <= end) {
int mid = (start + end) / 2;
if (matrix[row][mid] == target) {
return true;
}
if (matrix[row][mid] > target) {
end = mid - 1;
}else {
start = mid + 1;
}
}
return false;
}
};
No comments:
Post a Comment