题目
二维数组中的查找。
在一个 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。
题解一(类似二叉搜索树):
解法:类似于二叉搜索树,对于每个元素,从上到下递减,从左到右递增,利用这种特性,从左上角或者右下角开始搜索(根节点),遇到比target大的值就向左,反之向右
时间复杂度O(m+n),空间复杂度O(n)
python3:
class Solution:
def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
if matrix != []:
row, column = 0, len(matrix[0]) - 1
while row < len(matrix) and column >= 0:
if matrix[row][column] > target:
column -= 1
elif matrix[row][column] < target:
row += 1
else:
return True
return False
C++:
class Solution {
public:
bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
int i = matrix.size() - 1, j = 0;
while(i >= 0 && j < matrix[0].size()){
if(matrix[i][j] > target) i--;
else if(matrix[i][j] < target) j++;
else return true;
}
return false;
}
};