在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
示例:
现有矩阵 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]
]
给定 target = 5,返回 true。
给定 target = 20,返回 false。
限制:
0 <= n <= 1000
C++代码
思路:每一次与右上角的数字进行比较,大于右上角的数字,之前的行的数字都小,所以要加一行
小于右上角的数字,右边的列都比这个数字大,所以只搜索左边的列
class Solution {
public:
bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
int row = matrix.size();//行数
if (row == 0) {
return false;
}
int column = matrix[0].size();//列数
int i = 0, j = column - 1;
while (i < row && j >= 0){
if (matrix[i][j] == target){
return true;
}
else if(matrix[i][j]>target){
j--;
}
else{i++;}
}
return false;
}
};
测试代码
(假如你想在自己本地测试)
int main()
{
vector<vector<int>> a(5, vector<int>(5));
a= {
{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 b = 5;
Solution s;
bool c =s.findNumberIn2DArray(a, b);
cout << c << endl;
return 0;
}