74. 搜索二维矩阵
我能想到的笨方法:用两次二分查找,先二分找到要查找元素应该在的一行,然后在该行二分。
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int rows = matrix.size();
int cols = matrix[0].size();
int l = 0, r = rows - 1;
while(l + 1 < r){
int m = (l + r) / 2;
if(target == matrix[m][0]) return true;
if(target > matrix[m][0]){
l = m;
}
else{
r = m;
}
}
if(target >= matrix[r][0]) l = r;
int l2 = 0, r2 = cols - 1;
while(l2 + 1 < r2){
int m = (l2 + r2) / 2;
if(target == matrix[l][m]) return true;
if(target > matrix[l][m]){
l2 = m;
}
else{
r2 = m;
}
}
if(matrix[l][l2] == target || matrix[l][r2] == target) return true;
else return false;
}
};
其实一次二分查找就可以了,若将矩阵每一行拼接在上一行的末尾,则会得到一个升序数组,我们可以在该数组上二分找到目标元素。
代码实现时,可以二分升序数组的下标,将其映射到原矩阵的行和列上。
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m = matrix.size(), n = matrix[0].size();
int low = 0, high = m * n - 1;
while (low <= high) {
int mid = (high - low) / 2 + low;
int x = matrix[mid / n][mid % n];
if (x < target) {
low = mid + 1;
} else if (x > target) {
high = mid - 1;
} else {
return true;
}
}
return false;
}
};