Find in 2D Array

code show as below:

public class Demo1 {
    public static void main(String[] args) {
        int [][] arr=new int[][]{{1,2,8,9},
                                 {2,4,9,12},
                                 {4,7,10,13},
                                 {6,8,11,15}};
        int a=12;
        System.out.println(Demo1.find(arr,a));
    }
    public  static  boolean find( int [][] arr, int number){
         boolean flag = false ;
         int rows=arr[0].length; // Number of rows 
        int columns=arr.length; // Number of columns 
        if ( rows> 0 && columns>0 ){
            int row=0 ;
            int column = columns - 1 ;
            while ( row >=0 && row < rows && column >= 0 ){
                 // If it is smaller than number, it means not in this row, let Number of rows + 1 
                if ( arr[row][column] < number ){
                    ++row;
                }
                // If it is larger than number, it means that it is not in this column, let the number of columns -1 
                else  if (arr[row][column] > number){
                     -- column;
                } else  
                    return  true ;
            }
        }
        return  flag;
    }

The analysis diagram is as follows:

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325242184&siteId=291194637