题目描述
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
第一种实现:数组
bool Find(int target, int rows, int cols, int* array)
{
bool isFound = false;
if(array != nullptr && rows > 0 && cols > 0)
{
int row = 0, col = cols - 1;
while(row<rows&&col>=0)
{
int cmp = array[row*cols+col];
if(cmp == target)
{
isFound=true;
cout<<"target position: "<<row<<"row "<<col<<" column"<<endl;
break;
}
else if(cmp>target)
{
--col;
}
else
{
++row;
}
}
}
return isFound;
}
第二种实现:向量vector(从右上角开始比较)
bool Find(int target, vector<vector<int>> array) {
int rows = array.size();
int cols = array[0].size();
bool isFound = false;
if(rows > 0 && cols > 0)
{
int row = 0, col = cols - 1;
while(row<rows&&col>=0)
{
int cmp = array[row][col];
if(cmp == target)
{
isFound=true;
cout<<"target position: row"<<row<<",column"<<col<<endl;
break;
}
else if(cmp>target)
{
--col;
}
else
{
++row;
}
}
}
return isFound;
}
第三种实现:向量(从左下角开始比较)
bool Find(int target, vector<vector<int>> array) {
int rows = array.size();
int cols = array[0].size();
bool isFound = false;
if(rows > 0 && cols > 0)
{
int row = rows-1, col = 0;
while(row>=0&&col<cols)
{
int cmp = array[row][col];
if(cmp == target)
{
isFound=true;
cout<<"target position: row "<<row<<",column "<<col<<endl;
break;
}
else if(cmp>target)
{
--row;
}
else
{
++col;
}
}
}
return isFound;
}
具体思路可以看以下链接的文章:
剑指Offer面试题:2.二维数组中的查找
剑指offer(C++)——二维数组中的查找
剑指offer (04):二维数组中的查找 (C++ & Python 实现)