这道题一开始以为纵向一次二分,然后再横向二分会比较快。
但其实把整个数组展开,二分查找O(log(mn)) = O(logm) + O(logn),其实一样。
两次查找的方法:
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m = matrix.size();
if(m == 0) return false;
int n = matrix[0].size();
if(n == 0) return false;
int i = 0, j = m - 1, mid;
while(i <= j){
mid = i + (j - i) / 2;
if(matrix[mid][0] == target){
return true;
} else if(matrix[mid][0] > target){
j = mid - 1;
} else {
i = mid + 1;
}
}
if(j < 0) return false;
int hit = j;
i = 0, j = n - 1;
while(i <= j){
mid = i + (j - i) / 2;
if(matrix[hit][mid] == target){
return true;
} else if(matrix[hit][mid] > target){
j = mid - 1;
} else {
i = mid + 1;
}
}
return false;
}
};
觉得还是一次遍历的更为简洁一点:
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m = matrix.size();
if(m == 0) return false;
int n = matrix[0].size();
if(n == 0) return false;
int i = 0, j = m * n;
int mid, mv;
while(i < j){
mid = i + (j - i) / 2;
mv = matrix[mid / n][mid % n];
if(mv == target){
return true;
} else if(mv > target){
j = mid;
} else {
i = mid + 1;
}
}
return false;
}
};