package q04;/**
* 在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。
* 请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
* @author asus
*
*/publicclassSolution{public boolean findNumberIn2DArray(int[][] matrix, int target){if(matrix ==null){returnfalse;}//matrix数组的总行数,总列数
int rows = matrix.length;//此处代码若没有,当matrix={}时,会出错if(rows <=0){returnfalse;}
int columns = matrix[0].length;//此处代码若没有,当matrix={{},{}}时,会出错if(columns <=0){returnfalse;}//从右上角开始检索
int row =0;
int column = columns-1;//持续检索直到数组下标越界,证明此数组中不存在target元素,返回falsewhile(row <= rows-1&& column >=0){//若找到此元素,返回trueif(target == matrix[row][column]){returntrue;}//若当前位置大于target,应当将范围向左移动if(target < matrix[row][column]){
column--;}else//若当前位置元素小于target,应当将范围向下移动{
row++;}}returnfalse;}}
测试部分代码
package q04;/**
* 在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。
* 请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
* @author asus
*
*/publicclassTestApp{publicstaticvoidmain(String[] args){// TODO Auto-generated method stub
int[][] array1 ={};
int[][] array2 ={{},{}};
int[][] array3 ={{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
Solution slt =newSolution();
boolean result;//array1为{},应当为false
result = slt.findNumberIn2DArray(array1,7);
System.out.println("7 is in the array1: "+ result);//array2为{{},{}},应当为false
result = slt.findNumberIn2DArray(array2,7);
System.out.println("7 is in the array2: "+ result);//8存在于array3,应当为true
result = slt.findNumberIn2DArray(array3,8);
System.out.println("8 is in the array3: "+ result);//16不存在与array3,应当为false
result = slt.findNumberIn2DArray(array3,16);
System.out.println("16 is in the array3: "+ result);}}