问题描述
力扣
在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
解题思路:选取数组中右上角的数字。如果该数字正好等于要查找的数字,则查找过程结束;>,删除这个数字的列;<,删除这个数字的行。这样缩小查找范围,找到查找数字,或者范围为空,说明没有这个数字。
解题代码
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
boolean found = false;
int rows = matrix.length; //获取二维数组行数
if (matrix != null && rows > 0) {
int columns = matrix[0].length; //获取二维数组列数
int row = 0;
int column = columns - 1;
while (row < rows && column >= 0) {
if (matrix[row][column] == target) {
found = true;
break;
} else if (matrix[row][column] > target) {
column--;
} else {
row++;
}
}
}
return found;
}
}
注意:必须加上
if (matrix != null && rows > 0) //rows>0是必须的
否则会报错:Index 0 out of bounds for length 0 ,解释:列数=数组名[0].length这句之前要判断数组是否为空,若为空则数组名[0]所代表的子数字不存在,会报错。当 matrix 为空时,访问 matrix 是不会报错的,但访问 matrix[0] 会报错。
时间复杂度:O(M+N),M,N为二维数组的行数和列数,空间复杂度O(1)。