- 1 public class No2Array {
- 2 public static void main(String[] args) {
- 3 int[][] array = {
- {
- 1,
- 2,
- 8,
- 9
- },
- 4 {
- 2,
- 4,
- 9,
- 12
- },
- 5 {
- 4,
- 7,
- 10,
- 13
- },
- 6 {
- 6,
- 8,
- 11,
- 15
- }
- };
- 7 System.out.println(findByTheUpperRightCorner(5, array));
- 8 System.out.println(findByTheLowerLeftCorner(7, array));
- 9
- }
- 10 11
- /*
- 12 * 选取数组查找范围内的右上角的数字,如果该数字等于要查找的数字,则查找结束。
- 13 * 如果该数字小于要查找的数字,则剔除该数字所在的行;
- 14 * 如果该数字大于要查找的数字,则剔除该数字所在的列;
- 15 */
- 16 public static boolean findByTheUpperRightCorner(int target, int[][] array) {
- 17
- if (array.length > 0) {
- 18 int rows = array.length;
- 19 int columns = array[0].length;
- 20 int row = 0;
- 21 int column = columns - 1;
- 22
- while (row = 0) {
- 23
- if (array[row][column] == target) 24
- return true;
- 25
- if (array[row][column] > target) 26 column--;
- 27
- else 28 row++;
- 29
- }
- 30
- return false;
- 31
- }
- 32
- return false;
- 33
- }
- 34 35
- /*
- 36 * 选取数组查找范围内的左下角的数字,如果该数字等于要查找的数字,则查找结束;
- 37 * 如果该数字小于要查找的数字,则剔除该数字所在的列;
- 38 * 如果该数字大于要查找的数字,则剔除该数字所在的行;
- 39 */
- 40 public static boolean findByTheLowerLeftCorner(int target, int[][] array) {
- 41
- if (array.length > 0) {
- 42 int rows = array.length;
- 43 int columns = array[0].length;
- 44 int row = rows - 1;
- 45 int column = 0;
- 46
- while (row >= 0 && column < columns) {
- 47
- if (array[row][column] == target) 48
- return true;
- 49
- if (array[row][column] < target) 50 column++;
- 51
- else 52 row--;
- 53
- }
- 54
- return false;
- 55
- }
- 56
- return false;
- 57
- }
- 58
- }
来源: http://www.cnblogs.com/gl-developer/p/6431331.html