题目描述
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
方法1:暴力破解,先比较第一行第一个元素,如果target大于该元素,横向查找,如果查找不到结果继续查找下一行;如果target等于该元素,直接输出。
public static boolean find(int[][]array,int target) {
if (array == null || array.length < 1 || array[0].length < 1) {
return false;
}
int rows = array.length;
int cols = array[1].length;
for (int i = 0; i < rows; i++) {
if(array[i][0]<target){
for (int j = 0; j < cols; j++) {
if(array[i][j]==target)
return true;
if(array[i][j]>target)
break;
}
}else if(array[i][0]==target){
return true;
}
}
return false;
}
方法2:每次选取右上角的数字,如果右上角数字>target,那么第四列整列都比target大,可以删掉,col-1;如果右上角数字<target,那么第一行整行都比target小,可以删掉,rol+1。以此类推直到找到等于target的数。
public static boolean find1(int[][]array,int target) {
if (array == null || array.length < 1 || array[0].length < 1) {
return false;
}
int rows = array.length;
int cols = array[1].length;
int row = 0;
int col = cols - 1;
while (row >= 0 && row < rows && col >= 0 && col < cols) {
if (array[row][col] == target) {
return true;
} else if (array[row][col] > target) {
col--;
} else {
row++;
}
}
return false;
}
来源:CSDN
作者:Java小白白又白
链接:https://blog.csdn.net/qq_36756682/article/details/103651861