/**
*
* @author 毛二
* @data 2015-8-8
* @comments
* 二维数组中的查找。其中二维数组,每行数递增。每列数也递增。
* 那么,二维数组右对角线上每一个数(x)构成了一个边界值。
* 所有x那行,在他左边 都是比他小的;所有x那列在他下面的都是比他大的。
*/
public class FindTarget {
public boolean Find(int [][] array,int target) {
//判断边界值
if(array== null ){
System.out.println("false");
return false;
}
int rows = array.length;
if(rows== 0){
System.out.println("false");
return false;
}
int cols = array[0].length;
if(cols== 0){
System.out.println("false");
return false;
}
System.out.println("rows = "+rows);
System.out.println("cols = "+cols);
//从右上角开始。逐步缩小数组的行列数
int row = 0,col = cols-1;
if(array[0][0] >target || array[rows-1][col] <target)
{
System.out.println("false");
return false;
}
if(rows > 0 && cols>0){
while(row <rows && col >=0){
if(array[row][col]==(target)){
System.out.println("true");
return true;
}
else if(array[row][col]>target){
col--;
}
else{
row++;
}
}
}
System.out.println("false");
return false;
}
public static void main(String[] args) {
int a[][] = { {1,2,8,9},
{2,4,9,12},
{4,7,10,13},
{6,8,11,15},
{6,8,11,15}
};
int b[][]=null;
int c[][ ] = new int[1][0];
FindTarget ft = new FindTarget();
ft.Find(c,16);
}
}
剑指offer刷题之java实现的二维数组中的查找
最新推荐文章于 2019-07-31 19:18:49 发布