题目描述
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
二分查找
解法一:暴力搜索
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
int rowcount = array.size();
int colcount = array[0].size();
if(rowcount == 0 || colcount == 0) return false;
for(int i = 0; i < rowcount; i++)
{
for(int j = 0; j < colcount; j++)
{
if(array[i][j] == target) return true;
}
}
return false;
}
};
暴力搜索第一个版本的 ,在第二个版本中同样借助暴力搜索我们可以将时间复杂度缩减为 :
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
if(array.size()!=0)
{
int row = 0;
int col = array[0].size() - 1;
while(row < array.size() && col >= 0)
{
if(array[row][col] == target) return true;
else if(array[row][col] > target) --col;
else ++row;
}
}
return false;
}
};
解法二:行上借助二分查找
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
int rowcount = array.size();
int colcount = array[0].size();
int l, h, mid;
if(rowcount == 0 || colcount == 0) return false;
for(int i = 0; i < rowcount; i++)
{
l = 0; h = rowcount - 1;
while(l <= h)
{
mid = (l + h) / 2;
if(array[i][mid] < target) l = mid + 1;
else if(array[i][mid] > target) h = mid - 1;
else return true;
}
}
return false;
}
};
来源:CSDN
作者:白羊_Aries
链接:https://blog.csdn.net/qq_38204302/article/details/104144537