版权声明:转载请标明出处 https://blog.csdn.net/easy_purple/article/details/82991844
题目:
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
思路:
- 首选选取数组中右上角的数字。如果该数字等于要查找的数字,则查找过程结束;
- 如果该数字大于要查找的数字,则剔除这个数字所在的列;
- 如果该数字小于要查找的的数字,则剔除这个数字所在的行。这样每一步都能缩小范围。
(拓展思路:也可以首选数组左下角的数字。想一下为什么不首选左上角或者是右下角呢?)
代码:
package item1_10;
public class item_3_findNumber {
public static boolean item_3_findNumber(int[][] array, int num, int rows, int columns) {
if (array != null && rows > 0 && columns > 0) {
int row = 0;
int column = columns - 1;
while (row < rows && column >= 0) {
if (array[row][column] == num)
return true;
else if (array[row][column] > num) {
column--;
} else
row++;
}
}
return false;
}
public static void main(String[] args) {
int[][] array = { { 1, 2, 8, 9 }, { 2, 4, 9, 12 }, { 4, 7, 10, 13 }, { 6, 8, 11, 15 } };
System.out.println(item_3_findNumber(array, 8, 4, 4) + "");
}
}