[Swipe the question bank] Sword refers to Offer_ programming questions, search in a two-dimensional array

Lookup in a two-dimensional array

Title description

In a two-dimensional array (each one-dimensional array has the same length), 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 to determine whether the array contains the integer.

Solution 1: Violence

Insert picture description here

function Find(target, array)
{
    
    
    if(array.length == 0 || target == null) return false;
     
    for(let i = 0; i < array.length; i++){
    
    
        for(let j = 0; j < array[0].length ; j++){
    
    
            if(array[i][j] == target) return true;
        }
    }
    return false;
}

Time complexity: O(N 2 )

Space complexity: O(1)

Solution two:

According to the requirements of the title, each row is sorted in increasing order from left to right, and each column is sorted in increasing order from top to bottom. You can use this feature to search based on data.

  • From top to bottom in the rightmost column, find a number that is not less than the target, and then search from right to left. The target is either in this row or not found.

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-5ge7BKZM-1578546695120)(file:///C:\Users\Dell\AppData\Local\Temp\ksohtml2064 \wps2.jpg)]

function Find(target, array)
{
    
    
    if(array.length == 0 || target == null) return false;
     
    let i = 0,
        j = array[0].length - 1;
     
    while(i < array.length && j >= 0){
    
    
        if(array[i][j] == target) return true;
        if(array[i][j] > target) j--;
        else i++;
    }
    return false;
}

Time complexity: O(M + N) (row height + column height)

Space complexity: O(1)

Other solutions

The same idea as the second solution, starting from a certain corner, remove one line for each comparison until a matching line is found, and then search in that line.

Guess you like

Origin blog.csdn.net/weixin_42339197/article/details/103905806