1.暴力
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;
}
};
2.二分,一行行的进行二分搜索
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int row=matrix.size();
for(int i=0;i<row;i++){
int left=0,right=matrix[i].size()-1;
while(left<=right){
int middle=(left+right+1)>>1;
if(matrix[i][middle]==target){
return true;
}
if(matrix[i][middle]>target){
right=middle-1;
}else if(matrix[i][middle]<target){
left=middle+1;
}else{
return true;
}
}
}
return false;
}
};
3.考虑其递增
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int row=0;
int value=matrix[0].size()-1;
while(row<matrix.size() && value>=0){
if(matrix[row][value]>target){
value--;
}else if(matrix[row][value]<target){
row++;
}else{
return true;
}
}
return false;
}
};