1.把矩阵当成数组,进行二分查找【行优先】
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if (matrix.empty()) return false;
int n = matrix.size(), m = matrix[0].size(), l = 0, r = m * n;
while (l < r) {
int mid = (l + r) >> 1;
if (matrix[mid / m][mid%m] > target) r = mid;
else l = mid + 1;
}
--r;
return r >= 0 && matrix[r / m][r%m] == target;
}
};
2.先对行进行二分查找,再对列进行二分查找
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if (matrix.empty() || matrix[0].empty()) return false;
int n = matrix.size(), m = matrix[0].size(), l = -1, r = n - 1;
while (l < r) {
int mid = (l + r + 1) >> 1;
if (matrix[mid][0] < target) l = mid;
else r = mid - 1;
}
int k = l;
if (k + 1<n && matrix[k + 1][0] == target) return true;
if (k < 0) return false;
l = 0, r = m;
while (l < r) {
int mid = (l + r) >> 1;
if (matrix[k][mid] > target) r = mid;
else l = mid + 1;
}
--r;
return matrix[k][r] == target;
}
};