在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
时间限制:1秒
空间限制:32768K
热度指数:408704
这题的关键是首先把位置定义在第一行的最后一个数字,如果target小于这个数字,那么列数减去一,然后逐个查找,如果target大于这个数字,那么行数加一,继续寻找下一行的数字。
package nowcoder;
public class no1 {
public static void main(String[] args)
{
int [][] a = new int [][]{{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
System.out.println(Find(-2,a));
}
public static boolean Find(int target, int [][] array) {
boolean result=false;
int rows=array.length;
int columns=array[0].length;
if(target>array[3][3])
result=false;
else if(array!=null&&rows>=0&&columns>=0)
{
int row=0;
int column=columns-1;
while(row>=0&&column>=0)
{
int tempvalue=array[row][column];;
if(target<tempvalue)
column--;
else if(target>tempvalue)
row++;
else {
result=true;
break;
}
}
}
return result;
}
}
输出结果:false