题目描述
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
思路:
- 暴力查找,复杂度O(n*m)
- 数组在某种程度是有序的,可以从右上角或者左下角开始判断筛选,逐渐缩小范围,最坏的复杂度O(n + m)
AC代码
class Solution
{
public:
// bool Find(int target, vector<vector<int>> array) {
// for (int i = 0;i < array.size();i++)
// {
// for (int j = 0;j < array[i].size();j++)
// {
// if (target == array[i][j])
// return true;
// }
// }
// return false;
// }
bool Find(int target, vector<vector<int>> array)
{
int row = array.size(); //行数
int col = array[row-1].size(); //列数 注意这里求要将row-1
//cout << row << " " << col << endl;
if (row >0 && col >0)
{
row = 0;
col = col-1;
while (row <= array.size()-1 && col >= 0)
{
if (array[row][col] == target)
{
//cout << "找到了e" <<endl;
return true;
}
else if (array[row][col] > target)
col--;
else
{
row++;
}
}
}
//cout << "没有" ;
return false;
}
};
总结:
- 好像没什么可以总结的,学到的就是vector定义一个二维数组,
vector<vector<int>> array(4, vector<int>(4)); //定义一个二维数组4x4
来源:CSDN
作者:chenchenxiaojian
链接:https://blog.csdn.net/weixin_42100456/article/details/103916293