第一种: 直觉, 遍历
遍历整个二维数组, 如果找到了, 则返回 true; 否则, 返回 false.
public class Solution {
public boolean Find(int target, int [][] array) {
if(array == null || array.length == 0 || array[0].length == 0)
return false;
// 二维数组的行数和列数
int numRows = array.length, numColumns = array[0].length;
// 遍历二维数组
for(int i = 0; i < numRows; ++i)
{
for(int j = 0; j < numColumns; ++j)
{
if(array[i][j] == target)
return true;
}
}
return false;
}
} 第二种: 遍历过程中稍微利用一点数组有序的特点
该二维数组有一个特点.
越右边的数越大, 越下边的数越大.
那么每次遍历的时候先比较一下范围, 如果目标值在该行(列)的区间内, 那么是有可能存在目标值的; 否则, 不可能存在目标值.
对于不存在目标值的行(列), 不需要遍历; 有可能存在目标值的行(列), 则进行遍历.
例如,
[
[1,2,8,9],
[2,4,9,12],
[4,7,10,13],
[6,8,11,15]
]
中, 目标值 target = 7.
第 1 行数的范围是 [1, 9], 可能存在 target, 进行遍历, 结果没找到 target, 继续下一行;
第 2 行数的范围是 [2, 12], 可能存在 target, 进行遍历, 结果没找到 target, 继续下一行;
第 3 行数的范围是 [4, 13], 可能存在 target, 进行遍历, 找到 target, 结束查找.
第 1 列数的范围是 [1, 6], 不可能存在 target, 则不需要遍历;
第 2 列数的范围是 [2, 8], 可能存在 target, 进行遍历, 并找到 target, 结束查找.
public class Solution {
public boolean Find(int target, int [][] array) {
if(array == null || array.length == 0 || array[0].length == 0)
return false;
// 二维数组的行数和列数
int numRows = array.length, numColumns = array[0].length;
for(int i = 0; i < numRows; ++i)
{
// 首先遍历每一行的第一个元素和每一行的最后一个元素
if(array[i][0] <= target && target <= array[i][numColumns - 1])
{
for(int j = 0; j < numColumns; ++j)
{
if(array[i][j] == target)
{
return true;
}
}
}
}
return false;
}
} 第三种: 右上角法 (我的脑瓜是想不出来地, 看了大家的题解, 才搞懂了)
算法:
1、从二维数组的右上角开始查找;
2、如果当前值等于 target, 成功找到, 结束查找, 返回 true;
3、如果当前值比 target 小, 则往下查找 (因为下边的数比当前数更大, 往下走才有可能找到 target);
4、如果当前值比 target 大, 则往左查找 (因为左边的数比当前数更小, 往左走才有可能找到 target);
5、下标超过了左边界或者下边界时, 查找失败, 返回 false.
public class Solution {
public boolean Find(int target, int [][] array) {
if(array == null || array.length == 0 || array[0].length == 0)
return false;
// 二维数组的行数和列数
int numRows = array.length, numColumns = array[0].length;
int i = 0, j = numColumns - 1, value;
while(0 <= i && i < numRows && 0 <= j && j < numColumns)
{
value = array[i][j];
if(value == target)
return true;
else if(value < target)
++i;
else
--j;
}
return false;
}
} 


京公网安备 11010502036488号