/*
* 在一个二维数组中,
* 每一行都按照从左到右递增的顺序排序,
* 每一列都按照从上到下递增的顺序排序。
* 请完成一个函数,输入这样的一个二维数组和一个整数,
* 判断数组中是否含有该整数。
*/
public static void main(String[] args) {
int[][] array = {{1,2,3},{4,5,6},{7,8,9}};
System.out.println(Find2(1, array));
}
/*
* 思路一:暴力遍历法 运行时间:224ms
*/
public static boolean Find(int target, int [][] array) {
int row = array.length;
int col = array[0].length;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if(array[i][j] == target) {
return true;
}
}
}
return false;
}
/*
* 思路二:由于该数组每一行从左到右递增,每一列从上到下递增,因此只需比较左上角的数字即可 运行时间:220ms
*/
public static boolean Find2(int target, int [][] array) {
int row = array.length;
int col = array[0].length;
if(row == 0 || col == 0) {
return false;
}
for (int i = 0; i < row; i++) {
//大于右上角的数,说明该行没有这个数,剔除掉这一行
if(target > array[i][col - 1]) {
continue;
} else if(target == array[i][col - 1]){ //=直接返回true
return true;
} else { //小于剔除掉这一列,并遍历该行
col--;
for (int j = 0; j < col; j++) {
if(target == array[i][j]) {
return true;
}
}
}
}
return false;
}本文出自 “12212886” 博客,请务必保留此出处http://12222886.blog.51cto.com/12212886/1963236
原文:http://12222886.blog.51cto.com/12212886/1963236