二维数组中的查找

在一个二维数组中(每个一维数组的长度相同),
每一行都按照从左到右递增的顺序排序,
每一列都按照从上到下递增的顺序排序。
请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
 
 
思路:选取右上角元素,
  元素大于Key--》剔除整列,
  元素小于key--》剔除整行*/
 
 
注意点就是循环的条件
对于row行 从上0开始递增,停止的条件是小于行的长度
对于column列,从右边列的长度开始递减,停止的条件是大于等于零
(因为查询最右下角的元素时,第0列是允许的不能停止
--------------------- 

 

 

 1 public static boolean Find(int target, int [][] array) {
 2 
 3     int row = 0;
 4     int col = array[0].length - 1;//
 5 
 6     while (row < array.length && col >= 0) {//保持一个数组
 7 
 8         if (target == array[row][col]) {
 9             return true;
10         }
11         if (array[row][col] < target) {
12             row++;
13             continue;
14         }
15         if (array[row][col] > target) {
16             col--;
17             continue;
18         }
19 
20     }
21 
22     return false;
23 
24 }

 

  

 

posted @ 2019-01-02 11:06  sup_liu9504  阅读(105)  评论(0)    收藏  举报