当前位置:网站首页>Sword finger offer 04 Search in two-dimensional array

Sword finger offer 04 Search in two-dimensional array

2022-07-05 04:17:00 xzystart

In a n * m In a two-dimensional array , Each row is sorted in ascending order from left to right , Each column is sorted in ascending order from top to bottom . Please complete an efficient function , Enter such a two-dimensional array and an integer , Determine whether the array contains the integer .

Example :

The existing matrix matrix as follows :

[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
Given target = 5, return true.

Given target = 20, return false.

Limit :

0 <= n <= 1000

0 <= m <= 1000

class Solution {
    
  public  static boolean findNumberIn2DArray(int[][] matrix, int target) {
    
    
        int  cloumn= 0,row = matrix.length-1;   // Position the subscript to the lower left corner of the matrix 
        // Because starting from the lower left corner or the upper right corner , That is, this array can be regarded as a binary search tree 



        while ((row>=0)&&cloumn<matrix[0].length){
      // Traversing the binary search tree 

            if (matrix[row][cloumn] >target){
    
                row--;

            }else if (matrix[row][cloumn] < target){
    
                cloumn++;

            }else return true;

        }
        return false;
    }
}

 Please add a picture description

原网站

版权声明
本文为[xzystart]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140648405690.html