[Jianzhi Offer Second Edition JAVA Implementation] [Interview Question 4: Finding in a Two-Dimensional Array]

Topic: In a two-dimensional array, each row is sorted in increasing order from left to right, and each column is sorted in increasing order from top to bottom. Please complete a function, input such a two-dimensional array and an integer, and determine whether the array contains the integer.


 

Ideas:

Find from the upper right corner or lower left corner, delete line by line, or use the dichotomy to find

Code:

 1 public class Test4 {
 2     public static boolean find(int[][] array,int target){
 3         if (array==null){
 4             return false;
 5         }
 6         int row=0;
 7         int column=array[0].length-1;
 8 
 9         while (row<array.length && column>=0){
10             if (array[row][column]==target){
11                 return true;
12             }
13             if (array[row][column]>target){
14                 column--;
15             }else{
16                 row++;
17             }
18         }
19         return false;
20     }
21 
22     public static void main(String[] args) {
23         int[][] array ={{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
24         System.out.println(find(array,7));
25     }
26 }

operation result:

Guess you like

Origin www.cnblogs.com/lkylin/p/12750982.html