剑指offer算法 java实现
题目:
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上往下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该函数。
例如下面的二维数组就是每行、每列都是递增排序。如果在这个数组中查找数字7,则返回true,如果查找数组5,由于数组中不含有该数字,则返回false。
1 2 8 9
2 4 9 12
4 7 10 13
6 8 11 15
当我们解决一个问题的时候,一个很有效的方法就是从一个具体的问题入手,通过分析简单具体的例子,试图寻找普遍的规律。
- package com.ynu.www.offer;
-
- public class FindFromMatrix {
-
- private static int[][] sample = new int[][] { { 1, 2, 8, 9 },
- { 2, 4, 9, 12 }, { 4, 7, 10, 13 }, { 6, 8, 11, 15 } };
-
- public static void printSample() {
- for (int i = 0; i < sample.length; i++) {
- for (int j = 0; j < sample[i].length; j++) {
- System.out.print(sample[i][j] + " ");
- }
- System.out.println();
- }
- }
-
- public static boolean getValuefromMatrix(int[][] sample, int rows,
- int columns, int num) {
- boolean found = false;
- if (sample != null && rows > 0 && columns > 0) {
- int row = 0;
- int column = columns - 1;
- while (row < rows && column >= 0) {
- int tempValue = sample[row][column];
- if (num > tempValue) {
- ++row;
- } else if (num < tempValue) {
- --column;
- } else {
- found = true;
- break;
- }
- }
- }
-
- return found;
- }
-
- public static void main(String[] args) {
- printSample();
- System.out.println(getValuefromMatrix(sample, 4, 4, 7));
-
- }
- }
根据分析,我们每次都选取数组查找范围的右上角数字,同样,我们可以选取左下角的数字,但是我们不能选择左上角或者右下角,因为无法缩小查找范围。