笔记 二维数组中的查找

来源:互联网 发布:photoshop盖印图层 mac 编辑:程序博客网 时间:2024/05/22 03:47

总结

从右上角开始判定,可以一次排除一列或者一行的数据右上角的坐标是row=0,column=columns-1,如果大于Number,说明在左边,column-1,如果小于Number,说明在下面,row+1
package findInMatrix;public class FindInMatrix {    public static void main(String[] args) {        // TODO Auto-generated method stub        test1();        test2();    }    static void test1() {        int matrix[][] = { { 1, 2, 8, 9 }, { 2, 4, 9, 12 }, { 4, 7, 10, 13 },                { 6, 8, 11, 15 } };        System.out.println(find(matrix, 1));    }    static void test2() {        System.out.println(find(null, 7));    }    static boolean find(int[][] matrix, int number) {        boolean found = false;        if (matrix != null) {            int rows = matrix.length;            int columns = matrix[0].length;            int row = 0;            int column = columns - 1;            while (row < rows && column >= 0) {                if (matrix[row][column] == number) {                    found = true;                    break;                } else if (matrix[row][column] > number) {                    --column;                } else {                    ++row;                }            }        }        return found;    }}
0 0