面试题4:二维数中的查找
题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
public class FindInPartiallySortedMatrix {
private static boolean find(int[][] matrix, int rows, int columns, int number) {
if (matrix != null && rows > 0 && columns > 0) {
int row = 0;
int column = columns - 1;
while (row < rows && column >=0) {
if (matrix[row][column] == number) {
return true;
} else if (matrix[row][column] > number) {
column--;
} else if (matrix[row][column] < number) {
row++;
}
}
}
return false;
}
public static void main(String[] args) {
int[][] matrix = {{1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15}};
System.out.println(find(matrix, 4, 4, 7));
}
}
运行结果:
true
- 另一种是从左下角开始,只要row和column交换就行。
- 还有其他的测试用例,但我没懂,还是如题目的二维数组结构,还是其他的。要是如题的话,多简单啊。要是随机的话,题目还有什么意义呢?
- 哎,还是太笨了。一个马虎让我找错半天。无颜再见江东父老啊,让孤自刎乌江吧~~~~