题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
思路:
{1, 3, 6, 9},
{2, 5, 7, 12},
{6, 10, 14, 18},
{8, 11, 15, 20}};
行:从上到下递增,列:从左到右递增
选择右上角9位置为参照,如key=9返回找到;如果key<9,列左移一个单位,还是比6小,列继续左移,即cum–;如果key>9,行向下移动一个单位,同理row++;
Java实现
public class ArrayFindKey {
public static void main(String[] args) {
int[][] arr = {
{1, 3, 6, 9},
{2, 5, 7, 12},
{6, 10, 14, 18},
{8, 11, 15, 20}};
int key = 6;
System.out.println( findKey(arr, key));
}
/**
* 从右上角开始,如果key,等于该值返回,小于该值,cums左移一个单位,如果大于该值rows下移一个单位
*
* @param arr
* @param key
*/
private static boolean findKey(int[][] arr, int key) {
int rows = 0;
int cums = arr[0].length - 1;
while (rows < arr.length && cums >= 0) {
if (arr[rows][cums] == key) {
showLog(rows, cums);
return true;
} else if (arr[rows][cums] < key) {
rows++;;
} else if (arr[rows][cums] > key) {
cums--;
}
}
return false;
}
private static void showLog(int rows, int cums) {
System.out.println("找到原素 arr[" + rows + "][" + cums+"]");
}
}