二维数组中的查找

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

                                    

 1 /*二维数组查找*/
 2     public boolean findNumberIn2DArray(int[][] matrix, int target) {
 3         /*matrix.length指的是行数*/
 4         if ((matrix == null || matrix[0].length == 0) || (matrix.length == 1 && matrix[0].length == 0)) {
 5             return false;
 6         }
 7         int i = 0;  //
 8         int j = matrix[0].length - 1;  //
 9         while (i <= matrix.length-1 && j >= 0) {
10             if (matrix[i][j] == target) {
11                 return true;
12             } else if (target < matrix[i][j]) {
13                 j--;
14             } else {
15                 i++;
16             }
17         }
18         return false;
19     }

 

posted @ 2020-08-01 12:05  王余阳  阅读(119)  评论(0)    收藏  举报