描述
写出一个高效的算法来搜索 m × n矩阵中的值。
这个矩阵具有以下特性:
- 每行中的整数从左到右是排序的。
- 每行的第一个数大于上一行的最后一个整数。
您在真实的面试中是否遇到过这个题? 是
样例
考虑下列矩阵:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
给出 target = 3
,返回 true
挑战
O(log(n) + log(m)) 时间复杂度
代码:
class Solution {
public:
/**
* @param matrix: matrix, a list of lists of integers
* @param target: An integer
* @return: a boolean, indicate whether matrix contains target
*/
bool searchMatrix(vector<vector<int>> &matrix, int target) {
// write your code here
if (matrix.empty() ||matrix[0].empty()) return false;//此处不能用r=matrix.size()和c=matrix[0].size()代替,不知道为什么????
if (target < matrix[0][0] || target >matrix.back().back()) return false;
int left=0,right=matrix.size()-1;
while(left<=right)//先用二分法找到其所在的行,其中right的值为其行值
{
int mid=(left+right)/2;
if(target<matrix[mid][0])
right=mid-1;
else if(target>matrix[mid][0])
left=mid+1;
else return true;
}
int row=right;
left=0;
right=matrix[0].size()-1;
while(left<=right)//再用二分法在所在行查找
{
int mid=(left+right)/2;
if(target<matrix[row][mid])
right=mid-1;
else if(target>matrix[row][mid])
left=mid+1;
else
return true;
}
return false;
}
};