问题描述
在一个二维数组中,
每一行都按照从左到右递增的顺序排序,
每一列都按照从上到下递增的顺序排序。
请完成一个函数,输入这样的一个二维数组和一个整数,
判断数组中是否含有该整数。
Consider the following matrix:
{
{1, 4, 7, 11, 15},
{2, 5, 8, 12, 19},
{3, 6, 9, 16, 22},
{10, 13, 14, 17, 24},
{18, 21, 23, 26, 30}
}
Given target = 5, return true.
Given target = 20, return false.
解题思路
- 遍历
- 如何遍历能不断缩小区间
- 从矩阵右上角开始,当前元素的查找区间为左下角的所有元素,利用while循环
- 复杂度:O(M + N) + O(1)
代码
#include <iostream>
#include <vector>
#include <string>
using namespace std;
//note:缩小查找区间
class Solution
{
public:
bool Find(int target, vector<vector<int>> array)
{
if (array.empty())
return false;
int row = array.size();
int col = array[0].size();
int curRow = 0;
int curCol = col - 1;
while (curRow < row && curCol >= 0)
{
if (target == array[curRow][curCol])
return true;
else if (target < array[curRow][curCol])
curCol--;
else
curRow++;
}
return false;
}
};
int main()
{
Solution sol;
vector<vector<int>> array =
{
{1, 4, 7, 11, 15},
{2, 5, 8, 12, 19},
{3, 6, 9, 16, 22},
{10, 13, 14, 17, 24},
{18, 21, 23, 26, 30}
};
int target = 1;
bool result = sol.Find(target, array);
cout << boolalpha << result << endl;
system("pause");
return 0;
}