题目描述
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
示例
Consider the following 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]
]
Given target = 5, return true.
Given target = 20, return false.Copy to clipboardErrorCopied
思路
该二维数组中的一个数,小于它的数一定在其左边,大于它的数一定在其下边。因此,从右上角开始查找,就可以根据 target 和当前元素的大小关系来缩小查找区间,当前元素的查找区间为左下角的所有元素。
右上查找
public class Solution {
public boolean Find(int target, int [][] array) {
if(array == null || array.length == 0 || array[0].length == 0) {
return false;
}
int rows = array.length;
int cols = array[0].length;
// 右上
int r = 0;
int c = cols-1;
while(r < rows && c >= 0){
if(array[r][c] < target){
r++;
}else if(array[r][c] > target){
c--;
}else{
return true;
}
}
return false;
}
}
左下查找
public class Solution {
public boolean Find(int target, int [][] array) {
if(array == null || array.length == 0 || array[0].length == 0) {
return false;
}
int row = array.length,cols = array[0].length;
int r = row - 1, c = 0;
while(r >= 0 && c < cols){
if(target == array[r][c]){
return true;
}else if(target > array[r][c]) {
c++;
}else {
r--;
}
}
return false;
}
}