当前位置:网站首页>Daily question - Search two-dimensional matrix PS two-dimensional array search

Daily question - Search two-dimensional matrix PS two-dimensional array search

2022-07-05 05:28:00 ThE wAlkIng D

Title Description

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 a function , Enter such a two-dimensional array and an integer , Determine whether the array contains the integer .

Problem analysis

If you want to find the fastest , You need to traverse from the lower left corner of the matrix , Because from the lower left corner , The number goes up and down , The number gets bigger to the right , When the target value is larger than the search value , Move upward , When the target value is smaller than the search value , Move right

Code instance

public class Solution {
    
    public boolean Find(int target, int [][] array) {
    
     int row = array.length-1;
        int col = 0;
        while((row >= 0)&&(col < array[0].length)){
    
            if(array[row][col] > target){
    
                row--;
            }else if(array[row][col] < target){
    
                col++;
            }else{
    
                return true;
            }
        }
        return false;
    }
}
原网站

版权声明
本文为[ThE wAlkIng D]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050525449871.html