题目
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
思路
既然数组是有规律的,传统的遍历肯定不是最优解。
假设有这样一个二维数组,我们要找的数字11
。
右上角的数字在所在行中是最大的,在所在列中是最小的。那我们就可以从右上角的数字出发,如果数字大于11
,则行号-1
;如果数字小于11
,则列号+1
。如果角标越界,则说明数字不存在。
实现
public static boolean find(int target, int [][] array) {
if(array[array.length-1].length==0){//二维数组为空时返回false
return false;
}
int currentRow=0;
int totalRow=array[0].length-1;
int currentCol=array.length-1;
while(array[currentRow][currentCol] != target){
if(array[currentRow][currentCol] > target){
currentCol--;
} else if(array[currentRow][currentCol] < target){
currentRow++;
} else{
return true;
}
if(currentCol < 0 || currentRow >totalRow){
return false;
}
}
return true;
}
题目来源:剑指offer