How to implement array lookup

Description of the problem on Niuke.com:

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.

I wrote a very simple secondary loop search myself. (I considered here that if it is not an array, I wanted to write a writing method of its own loop call, but it all failed ==!)

/**
 *
 * @param {number} target
 * @param {number[]} array
 */
function Find(target, array)
{
    var len = array.length;
    var flag = false;
    for(var i=0; i< len; i++) {
        var ele = array[i];
        if(typeof ele !== 'object') {
            if(target === ele) {
                flag = true;
                continue;
            }
        } else {
            var idx = ele.indexOf(target);
            //flag = (idx!=-1)&&true;
            if(idx !== -1) {
                flag = true;
            }
        }
    }
    return flag;
}

 

I found an idea in the Niuke online sharing area, because the topic descriptions are arranged in order from left to right, you can use the binary tree search method.

function Find(target, array) {
    for(var i=0; i<array.length; i++) {
        var low = 0,
            ele = array[i];
        var high = ele.length - 1;
        
        while(low <= high) {
            var mid = Math.floor((low+high)/2);
            if( target < ele[mid]) {
                high = mid - 1;
            }else if( target > ele[mid] ) {
                low = low + 1;
            } else {
                return true;
            }
        }
    }
    return false;
}

 

Guess you like

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