题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否有该整数。
思路:右上角第一个元素开始查找,如果第一个元素大于目标元素,因为每列都是从小到大排列的,则说明该列的所有元素都大于目标元素,所以可以把该列排除,接着看从右往左第二列,重复之前的操作,如果该列的第一个元素小于目标元素,因为每行是从小到大排列的,所以说明该行的所有元素都小于目标元素,所以可以把该行排除,以此类推。
代码:
public class ArrayFind {
public static void main(String[] args) {
int[][] max = {{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
boolean isFind = find(max, 4, 4, 5);
System.out.println("isFind: " + isFind);
boolean isFind1 = find(max, 4, 4, 7);
System.out.println("isFind: " + isFind1);
}
public static boolean find(int[][] matrix, int row, int col, int num) {
boolean found = false;
int rowIndex = 0;
int colIndex = col - 1;
if (matrix != null) {
while (colIndex >= 0 && rowIndex < row) {
if (matrix[rowIndex][colIndex] > num) {
colIndex--;
continue;
} else if (matrix[rowIndex][colIndex] < num) {
rowIndex++;
continue;
} else if (matrix[rowIndex][colIndex] == num) {
found = true;
break;
}
}
}
return found;
}
}