在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
例如下面的二维数组就是每行、每列都是递增排序,如果在这个数组中查找数字7,则放回true;如果查找数字5,由于数组不含该数字,则返回false。
1 2 8 9 2 4 6 12 4 7 10 13 6 8 11 15解题思路
首先选取数组中右上角的数字,如果该数字等于要查找的数字,那么查找过程结束。
如果该数字大于要查找的数字,则剔除这个数字所在的列,因为它所在的列的所有下方的值都比要查找的数字大。
如果该数字小于要查找的数字,则剔除这个数字所在的行,因为它所在的列的所有左侧的值都比要查找的数字小。
也就是说,如果查找的数字不在数组(新查找范围)的右上角,则每次都能剔除一行或者一列,每次都可以缩小查找的范围,直到找到要查找的数字,或者查找不到。
正确解题public class FindInPartiallySortedMatrix {
public static boolean find(int[] matrix, int rows, int columns, int number) {
boolean found = false;
// 过滤非法输入
if (matrix.length > 0 && rows > 0 && columns > 0) {
int row = 0;
int column = columns - 1;
// 防止出界
while (row < rows && column >= 0) {
if (matrix[row * columns + column] == number) {
found = true;
break;
}
else if (matrix[row * columns + column] > number) {
column--;
}
else {
row++;
}
}
}
return found;
}
// 测试
public static void main(String[] args) {
int[] matrix = {1,2,8,9,2,4,9,12,4,7,10,13,6,78,11,15};
boolean found = find(matrix, 4, 4, 7);
System.out.println("found "+found);
}
}
来自:
《剑指offer》
Coding-Interviews/二维数组中的查找.md at master · todorex/Coding-Interviews



