题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
功能代码如下:
/**
*既然需要从二维数组中查找是否含有指定的整数,充分利用二维数组每行从左到右递增,和每列从上到下递增的规律。
*此处我从右上角开始比较
*/
public class Solution{
public boolean Find(int target, int[][] array){
int rows = array.length;
int cols = array[0].length;
boolean found = false;
if(array!=null&&rows>0&&cols>0){
int row =0;
int col = cols-1;
if(target>array[row][col]){
row++;
}else if(target<array[row][col]){
col--;
}else{
found = true;
break;
}
}
return found;
}
}
包含测试用例的完整代码:
public class Solution {
private static int[][] array = new int[][]{{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
public static void main(String[] args) {
printTarget();
System.out.println(Find(1,array));
}
public static boolean Find(int target, int[][] array){
int rows = array.length;
int cols = array[0].length;
boolean found = false;
if(array!=null&&rows>0&&cols>0){
int row = 0;
int col = cols-1;
while(row<rows&&col>=0){
if(array[row][col]>target){
col--;
}else if(array[row][col]<target){
row++;
}
else{
found = true;
break; //不然就一直遍历二维数组,没有返回值。
}
}
}
return found;
}
public static void printTarget(){
for(int i=0;i<array.length;i++){
for(int j=0;j<array[i].length;j++){
System.out.print(array[i][j]+" ");
}
System.out.println();
}
}
}
结果
总结:这是一道简单的二维数组查找问题,查找并且判断的思路不唯一。