。。。剑指Offer之——二维数组中的查找。。。

 1 public boolean Find(int target, int[][] array) {
 2         // 1、判断输入进来的数组array是否为空,array == null
 3         // 2、判断输入进来的数组array的内容是否为空,array.length == 0
 4         if (array == null || array.length == 0) {
 5             return false;
 6         }
 7         //获得数组的行数
 8         int rows = array.length;
 9         //获得数组的列数
10         int columns = array[0].length;
11 //        一开始,指向第一行的最后一列那个数,即最右上角的那个数
12         int r = 0, c = columns - 1;
13 //        r代表指向行的指针,c代表指向列的指针,不能越界
14         while (r < rows && c >= 0) {
15 //            如果数组中,目标值(target)= 右上角的数字,则返回true
16             if(target==array[r][c]){
17                 return true;
18 //            如果数组中,目标值(target)> 右上角的数字,
19 //            则说明应该往数组下面去寻找target
20             }else if(target>array[r][c]){
21                 r++;
22 //            如果数组中,目标值(target)< 右上角的数字,
23 //            则说明应该往数组左边去寻找target
24             }else{
25                 c--;
26             }
27         }
28 //        如果代码执行到这里,说明没有找到target
29 //        因为,如果要是找到了target,一定在上面的while循环体里return true
30 //        因此,找不到,则返回false
31         return false;
32     }

 

原文地址:https://www.cnblogs.com/yingmeng/p/10767041.html