package cn.test;
/*
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,
每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,
判断数组中是否含有该整数。
*/
public class Test01 {
private static int[][] array = {{1,2,3,4,5},
{2,3,4,5,6},
{3,4,5,6,7},
{4,5,6,7,8}
};
public static void main(String[] args) {
// System.out.println(array.length);
Test01 test01 = new Test01();
System.out.println(test01.find(array, 4));
}
/*
从右上角或左下角开始找,逐行删除,或者用二分法查找
*/
public boolean find(int[][] array, Integer target) {
//为空自然返回false;
if (array == null) {
return false;
}
int row = 0;
int column = array[0].length-1; //列从右上角开始
while (row < array.length && column >= 0) { //逐行比较
/*
从右上角开始进行比较,如果含有改值就返回true
*/
if(array[row][column] == target) {
return true;
}
/*
因为行是自左向右递增的,所以当当前比较值大于目标值的时候,直接在同一行向左移动
*/
if(array[row][column] > target) {
column--;
} else {
/*
当在同一行中比较的时候,被比较的值大于数组中的值的时候(也大于改值所在行的左侧的数),就直接在同一列中向下移动
*/
row++;
}
}
return false;
}
}