二维数组找数

在一个向右有序以及向下有序的二维数组查找某一个给定的数是否存在。

    public boolean find(int[][] a, int target) {
        int rowCount = a.length;
        int colCount = a[0].length;
        System.out.println(rowCount + " " + colCount);
        // int flag = a[rowCount-1][0];
        int i = rowCount - 1;
        int j = 0;
        while (j < colCount && i >= 0) {    //注意 i的取值范围为 〉=0,否则右上角的值不能比较。
             if (a[i][j] == target) {
                return true;
            }
             if (a[i][j] > target) {
                i--;
            }else if(a[i][j] < target){
                j++;
            }
        }
        return false;
    }

 

posted @ 2017-08-16 16:48  halo-漾  阅读(131)  评论(0编辑  收藏  举报