两次二分查找
时间复杂度:O(logN+logM)
C++代码:
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if (matrix.empty())
return false;
if (matrix[0].empty())
return false;
int row = matrix.size(), col = matrix[0].size();
if (target<matrix[0][0] || target>matrix[row - 1][col - 1])
return false;
int inf = 0, sup = row - 1, targetRow = 1;
while (1)
{
if (inf == sup)
{
targetRow = inf;
break;
}
if (inf + 1 == sup)
{
if (matrix[sup][0] == target)
return true;
else if (matrix[inf][0] == target)
return true;
else if (matrix[sup][0] < target)
targetRow = sup;
else
targetRow = inf;
break;
}
if (matrix[inf][0] == target)
return true;
if (matrix[sup][0] == target)
return true;
int mid = (sup + inf) / 2;
if (matrix[mid][0] > target)
{
sup = mid;
}
else if (matrix[mid][0] < target)
{
inf = mid;
}
else
return true;
}
return binary_search(matrix[targetRow].begin(), matrix[targetRow].end(), target);
}
};