题目:
题解1:暴力
最无脑的解法,遍历一遍二维数组,看看有没有相同的值。
时间复杂度:O(n*m)
空间复杂度:O(1)
题解2:线性查找
从二维数组的右上角开始查找。如果当前元素等于目标值,则返回 true
。如果当前元素大于目标值,则移到左边一列。如果当前元素小于目标值,则移到下边一行。
时间复杂度:O(n+m)
空间复杂度:O(1)
代码:
class Solution {
public:
bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
if(matrix.empty())return false;//为空时直接返回
//二维数组大小
int rows = matrix.size();
int cols = matrix[0].size();
//初始行列数
int cur_col = cols-1;
int cur_row = 0;
while(cur_col>=0 && cur_row<rows)
{
if(target==matrix[cur_row][cur_col])
{
return true;
}
else if(target>matrix[cur_row][cur_col])
{
cur_row++;
}
else
{
cur_col--;
}
}
return false;
}
};