题目链接
题目
在一个 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
0 <= m <= 1000
题解:
1.确定n,m n=matrix.length m=matrix[0].length, 同时要判断n,m是否介于0~1000之间
2.从二维矩阵的右上角(左移变小,下移变大)开始查找,当前元素等于target则返回true,当前元素小于target则下移,当前元素大于target则左移
也可从左下角开始查找(右移变大,上移变小)
证明:若当前元素num>target,则target必不在当前列,所以可消去当前列,行左移。若当前元素num<target,则target必不在num当前行,所以可消去当前行,列下移。
代码
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return false;
}
int rows = matrix.length;
int columns = matrix[0].length;
int row = 0;
int column = columns-1;
int num;
while(column>=0&&row<rows){
num =matrix[row][column];
if(num==target){
return true;
}
else if(num>target){
column--;
}
else{
row++;
}
}
return false;
}
}
错误代码
使用for循环跳过了可能的target
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
if(matrix==null||matrix.length==0||matrix[0].length==0){
return false;
}
for(int i=0;i<matrix.length-1;i++){
for(int j=matrix[0].length-1;j>0;j--){
if(matrix[i][j]==target){
return true;
}
if(matrix[i][j]<target){
i++;
}
else{
j--;
}
}
}
return false;
}
}
本文介绍了一种在递增排序的二维数组中查找特定整数的高效算法。通过从右上角开始,根据目标值调整搜索方向,实现了快速定位。文章提供了详细的算法步骤和示例代码,展示了如何避免无效搜索路径,提高查找效率。


被折叠的 条评论
为什么被折叠?



