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.
For example,
Consider the following matrix:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3
, return true
.
先确定在矩阵的哪一行进行查找,然在改行进行二分查找即可。当然可以通过下标的转换将整个矩阵当作一维数组来进行二分查找。
代码如下:
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if(matrix.empty() || matrix[0].empty())
return false;
int m = matrix.size();
int n = matrix[0].size();
int i=0;
while(i < m && target >= matrix[i][0])
i++;
if(i == 0)
return false;
int left=0,right=n-1,mid=0;
while(left<=right)
{
mid = (left+right)>>1;
if(matrix[i-1][mid] == target)
return true;
else if(matrix[i-1][mid] > target)
right = mid - 1;
else
left = mid + 1;
}
return false;
}
};