题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
代码如下:
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
//设置一个标识符,来判断是否查找到这个数字
bool found=false;
//获取array的大小
int Rows=array.size();
int Cols=array[0].size();
//检查输入数组的合法性
if(!array.empty()&&Rows>0&&Cols>0)
{
//从数组右上角的元素开始查找
int row=0;
int col=Cols-1;
//终止条件:行号逐渐增加,列号逐渐减小,谨防越界
while(row<Rows&&col>=0)
{
//当array[row][col]等于target
if(array[row][col]==target)
{
found=true;
break;
}
//当array[row][col]大于target,则需要往左列移动
else if(array[row][col]>target)
--col;
//当array[row][col]小于target,则需要往下一行移动
else
++row;
}
}
return found;
}
};
相关知识点:
1、数组的行列数;
include<iostream>
using namespace std;
int main()
{
int array[2][3] = { {1,2,3},{4,5,6} };
int rows = sizeof(array)/sizeof(array[0]);
int cols = sizeof(array[0]) / sizeof(int);
cout << rows << endl;
cout << cols << endl;
return 0;
}
2、容器的行列数;
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<vector<int> > array = { {1,2,3},{4,5,6} };
int rows = array.size();
int cols = array[0].size();
cout << rows << endl;
cout << cols << endl;
return 0;
}