题目描述:在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个高效的函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
来源:力扣(LeetCode)
示例:
现有矩阵 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。
方法一:首先判空,然后从右上角看,按二叉搜索树来查找:小于row++,大于col--,越界返回false。
python:
class Solution:
def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
if not matrix:
return False
row = 0
col = len(matrix[0])-1
while row <len(matrix) and col >= 0:
if matrix[row][col] > target:
col -= 1
elif matrix[row][col] < target:
row += 1
else:
return True
return False
java:
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
if(matrix == null || matrix.length == 0) {//对象不为空所以判断长度
return false;
}
int row=0;
int col=matrix[0].length-1;
while(row<matrix.length&&col>=0) {
if (matrix[row][col] > target)
col -= 1;
else if (matrix[row][col] < target)
row += 1;
else
return true;
}
return false;
}
}
c:
bool findNumberIn2DArray(int** matrix, int matrixSize, int* matrixColSize, int target){
if(matrix==NULL||matrixSize==0)
return false;
int row=0,col = *matrixColSize-1;
while(row<matrixSize&&col>=0){
if (matrix[row][col] > target)
col -= 1;
else if (matrix[row][col] < target)
row += 1;
else
return true;
}
return false;
}
方法二:直接从左到右从上到下逐一遍历查找。