嗯最近要秋招了,让自己进入一个编程的状态,既然写完代码,那就来捋下思路吧!
本题主要是考察二维数组的应用。
package jianzhioffer;
import java.util.Scanner;
/**
*题目: 在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
思路:从右上角开始找,这样每次能够去掉一行或者一列。
* @author Dan
*
*/
public class FindIn2Weishuzu {
public static void main(String[] args) {
/**
* 二维数组的定义和初始化
*/
int[][] a = { { 1, 2, 8, 9 }, { 2, 4, 9, 12 }, { 4, 7, 10, 13 }, { 6, 8, 11, 15 } };
boolean find7 = Find(7, a);
System.out.println(find7);
}
public static boolean Find(int target, int [][] array) {
//定义一个初值
boolean find = false;
//判断数组是否为空,否者会抛出空指针异常
if (array != null) {
//得到数组的行与列
int rows = array.length;
int columns = array[0].length;
//查找过程中的行与列
int row = 0;
int column = columns - 1;
while (row < rows && column >= 0) {
//每次从右上角开始查找,如果右上角比所找目标要大,说明右上角这一列都比该数大,可以删掉
if (array[row][column] > target) {
column--;//忽略该列
} else if (array[row][column] < target) {
//如果右上角比所找目标要小,说明右上角这一行都比该数小,可以删掉
row++;
} else {
//找到目标
find = true;
break;
}
}
}
return find;
}
}