原题链接:74. 搜索二维矩阵
solution: 暴力
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m = matrix.size();
int n = matrix[0].size();
for(int i = 0;i < m;i++)
for(int j = 0;j < n;j++)
if(matrix[i][j] == target) return true;
return false;
}
};
每一行进行二分
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m = matrix.size();
int n = matrix[0].size();
for(int i = 0;i < m;){
int l = 0,r = n - 1;
while(l < r){
int mid = l + r >> 1;
if(matrix[i][mid] >= target) r = mid;
else l = mid + 1;
}
if(matrix[i][l] == target) return true;
else i++;
}
return false;
}
};
将二维数组当成一维数组进行二分
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m = matrix.size();
int n = matrix[0].size();
int l = 0,r = m * n - 1;
while(l < r){
int mid = l + r >> 1;
if(matrix[mid / n][mid % n] >= target) r = mid;
else l = mid + 1;
}
if(matrix[l / n][l % n] == target) return true;
return false;
}
};