1.遍历每一行,在每一行中使用二分查找
class Solution {
public:
bool searchArray(vector<vector<int>> array, int target)
{
for(int i = 0;i < array.size();i++)
{
int l = 0, r = array[0].size() - 1;
while(l < r)
{
int mid = (l + r) >> 1;
if(array[i][mid] >= target)
{
r = mid;
}
else
{
l = mid + 1;
}
}
if(array[i][l] == target)
{
return true;
}
}
return false;
}
};
2.利用行为递增数列,列也为递增数列的性质,从右上角开始不断排除我们不需要的行和列
class Solution {
public:
bool searchArray(vector<vector<int>> array, int target)
{
if(array.size() == 0) return false;
int i = 0, k = array[0].size() - 1;
while(i < array.size() && k >= 0)
{
if(array[i][k] == target)
return true;
if(array[i][k] > target)
{
k--;
}
else if(array[i][k] < target)
{
i++;
}
}
return false;
}
};