剑指offer面试题3 二维数组中的查找 (java)

时间:2022-08-18 11:46:49

注:java主要可以利用字符串的length方法求出长度解决这个问题带来方便

 public class FindNum {
     public static void main(String[] args) {
         int arry[][] = {{1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15}};
         int findnum = 12;
         if(find(arry,findnum)){
             System.out.println("find");
         }
         else
             System.out.println("Not find");

     }

     private static boolean find(int[][] arry, int findnum) {
         if(arry==null){
             System.out.println("arry is null!");
             return false;
         }
         boolean findflag = false;//设置寻找标志
         int rows = arry.length;//获取二维数组总的行数
         int row  = 0;
         int colum = arry[0].length-1;//数组的列数
         while(row<rows&&colum>=0){
             if(arry[row][colum]==findnum){
                 findflag = true;
                 break;
             }
             else if(arry[row][colum]>findnum)
                 colum--;
             else
                 row++;

         }
         return findflag;

     }

 }