题目链接:https://leetcode-cn.com/problems/er-wei-shu-zu-zhong-de-cha-zhao-lcof/
在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
[
[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。
解法一:简单暴力
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
for (int i = 0; i < matrix.length; i++){
for (int j = 0; j < matrix[0].length; j++){
if (matrix[i][j] == target){
return true;
}
}
}
return false;
}
}
解法二:完美解决
该方法利用了这类矩阵的有序性。下面来慢慢分析(纪念我自己想到的解决方法,也纪念我的第一个双百,,啦啦啦啦 )
观察矩阵的数,在题目中也说明了矩阵的特点。就是从上向下递增,从左向右递增。现在想要从矩阵中找到一个数。难点在于怎么利用这个特性来解决这个问题?
再细想后发现,假如遍历时从左下角(当然右上角也可以)开始,当matrix[i][j]<target时,则说明第j列的数都要小于target,因此第j列的数不用再都遍历了,所以j++;当matric[i][j]>target时,则说明第i行的数不用再遍历了,因为第i行后面的数递增的,肯定比target大,所以i--;
这样就大幅度减少了遍历的次数,也很好的利用了该矩阵的特点。
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
if (matrix.length == 0){
return false;
}
int length = matrix[0].length, width = matrix.length;
int i = width - 1, j = 0;
while(i >= 0 && j < length){
if (matrix[i][j] == target){
return true;
}
else if (matrix[i][j] < target){
j++;
}
else{
i--;
}
}
return false;
}
}
与此类似的题目有:Number.378——有序矩阵中第K小的元素
解题过程参考:https://blog.csdn.net/weixin_43207025/article/details/107090067