C++【二维数组中的查找】
描述
在一个二维数组array中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一> 列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数> 组中是否含有该整数。
[
[1,2,8,9],
[2,4,9,12],
[4,7,10,13],
[6,8,11,15]
]
给定 target = 7,返回 true。
给定 target = 3,返回 false。
0 <= array.length <= 500
0 <= array[0].length <= 500
示例一:
输入:
7,[[1,2,8,9],[2,4,9,12],[4,7,10,13],[6,8,11,15]]
返回值:
true
说明:
存在7,返回true
示例二:
输入:
3,[[1,2,8,9],[2,4,9,12],[4,7,10,13],[6,8,11,15]]
返回值:
false
说明:
不存在3,返回false
参考程序一:
//暴力算法:直接遍历一遍数组,即可判断目标target是否存在。
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
// array是二维数组,这里没做判空操作
int rows = array.size();
int cols = array[0].size();
int i=rows-1,j=0;//左下角元素坐标
while(i>=0 && j<cols){//使其不超出数组范围
if(target<array[i][j])
i--;//查找的元素较少,往上找
else if(target>array[i][j])
j++;//查找元素较大,往右找
else
return true;//找到
}
return false;
}
};
参考程序二:
/*
思路:首先选取数组中右上角的数字。如果该数字等于要查找的数字,查找过程结束;
如果该数字大于要查找的数组,剔除这个数字所在的列;如果该数字小于要查找的数字,剔除这个数字所在的行。
也就是说如果要查找的数字不在数组的右上角,则每一次都在数组的查找范围中剔除一行或者一列,
这样每一步都可以缩小查找的范围,直到找到要查找的数字,或者查找范围为空。
*/
class Solution {
public:
bool Find(int target, vector<vector<int> > 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){
if(array[row][col] == target){
return true;
}
else if(array[row][col] > target){
--col;
}
else{
++row;
}
}
}
return false;
}
};