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
.
根据矩阵的性质可知
- 先判断该
target
可能所在的行 - 然后在判断改行中是否出现该值
- 两次判断都可以用二分
所以复杂度为O(log(n))
代码如下:
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if(matrix.size() == 0)
return false;
int b = 0, e = matrix.size()-1;
while(b < e)
{
int mid = b + (e - b + 1) / 2;
if(matrix[mid][0] == target)
return true;
else if(matrix[mid][0] < target)
b = mid;
else
e = mid - 1;
}
int x = 0, y = matrix[b].size() - 1;
while(x < y)
{
int mid = x + (y - x + 1) / 2;
if(matrix[b][mid] == target)
return true;
else if(matrix[b][mid] < target)
x = mid;
else
y = mid - 1;
}
if(b < matrix.size() && x < matrix[b].size() && matrix[b][x] == target)
return true;
return false;
}
};