2.二维数组中的查找

题目:

在一个二维数组中,每一行都按照从左到右递增的顺序排序每一列都按照从上往下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

例如下面的二维数组就是每行、每列都是递增排序。如果在这个数组中查找数字7,则返回true,如果查找数组5,由于数组中不含有该数字,则返回false。

1  2  8  9

2  4  9  12

4  7  10  13

6  8  11  15

当我们解决一个问题的时候,一个很有效的方法就是从一个具体的问题入手,通过分析简单具体的例子,试图寻找普遍的规律。

 总结查找的过程,我们发现如下规律:首先选取数组中右上角的数字,如果该数字等于要查找的数字,则查找过程结束;如果该数字大于要查找的数字,则剔除这个数字所在的列;如果该数字小于要查找的数字,则剔除这个数字所在的行。也就是说,如果要查找的数字不在数组 的右上角,则每一次都在数组的查找范围中剔除一行或者一列,这样每一步都可以缩小查找的范围,直到找到要查找的数字,或者查找范围为空。,在前面的分析中,我们每次都是选取数组查找范围内的右上角数字。同样,我们也可以选取左下角的数字。但是我们不能选择左上角数字或者右下角数字,因为这两个方向我们无法缩小查找的范围。

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));    

}    
}  

 测试用例:

二维数组中包含查找的数字

二维数组中没有要查找的数字

特殊输入测试(输入空指针)

原文地址:https://www.cnblogs.com/guweiwei/p/6840042.html