【剑指OFFER】二维数组的查找
题目描述:
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
题解:
首先自己做的时候,第一反应就是逐行查找,以下是自己第一次写的代码
public class Solution {
public boolean Find(int target, int [][] array) {
if (array == null) {
return false;
} else if (target < array[0][0]) {
return false;
} else {
for (int i = 0; i < array.length; i++) {
while (search(array[i], target)) {
return true;
}
}
return false;
}
}
public static boolean search(int[] a, int target) {
for (int i = 0; i < a.length; i++) {
if (a[i] == target) {
return true;
}else {
continue;
}
}
return false;
}
}
但是感觉这种方法有点笨,而且并没有用到 每一列都是按照从上到下递增的顺序排序 这个条件。
然后在评论区看到一个大神的思路,受教了
矩阵是有序的,从左下角来看,向上数字递减,向右数字递增, 因此从左下角开始查找,当要查找数字比左下角数字大时右移; 要查找数字比左下角数字小时,上移。
下面贴代码
public class Solution {
public boolean Find(int target, int [][] array) {
if(array == null) return false;
int rowCount = array.length;
int colCount = array[0].length;
int i,j;
for(i = rowCount-1,j = 0; i>=0 && j<colCount;){
if(array[i][j] == target) return true;
if(array[i][j] < target) {
j++;
continue;
}
if(array[i][j] > target){
i--;
continue;
}
}
return false;
}
}
本文介绍了一种高效的二维数组查找方法,利用数组的有序特性,从左下角开始比较目标值,实现快速查找。
265

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



