解法一:
二分搜索模板
while(l<=r)
{
mid=l+(l-r)/2;
if( <target) l=mid+1;
else if( >target) r=mid-1;
else //找到了;
}
没找到
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target)
{
if(matrix.empty() || matrix[0].empty()) return false;
int rmax=matrix.size(),cmax=matrix[0].size();
int l=0,h=cmax*rmax-1,mid=0;//双指针,将二维数组转化成一维
while(l<=h)
{
mid=l+(h-l)/2;
if(matrix[mid/cmax][mid%cmax]>target) h=mid-1;
else if(matrix[mid/cmax][mid%cmax]<target) l=mid+1;
else return true;
}
return false;
}
};
解法二:
class Solution {
public:
//题解1:暴力法
bool searchMatrix_1(vector<vector<int>>& matrix, int target) {
if(matrix.empty()||matrix[0].empty())return false;
for(const auto& m:matrix)//m是一位数组
{
if(find(m.begin(),m.end(),target)!=m.end())return true;
}
return false;
}
}