二维数组中的查找
题目描述
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
解题思路
从二维数组中的右上角或左下角开始作比较,每次比较要么查找命中,要么至少可以排除一行或者一列
代码
public class Solution {
public boolean Find(int target, int [][] array) {
if (array != null) {
int iMaxIndex = array.length - 1;
int jMaxIndex = array[0].length - 1;
// 从二维数组的右上角元素开始遍历
for (int i = 0; i <= iMaxIndex; i++) {
for (int j = jMaxIndex; j >= 0; j--) {
if (array[i][j] == target) {
return true;
} else if (array[i][j] < target) {
// 查找目标值比当前值大,可以排除当前行的所有元素
break;
} else {
// 查找目标值比当前值小,可以排除当前列的所有元素
jMaxIndex = j - 1;
}
}
}
}
return false;
}
}