Array prove safety Offer-

topic

(The length of each one-dimensional array of same), each row from left to right in order of ascending sort, to sort each column in a two-dimensional array in order of increasing from top to bottom. A complete function, enter such a two-dimensional array and an integer, it is determined whether the array contains the integer.

Thinking

  • Arrays are ordered, so we choose the upper right or lower left corner as the basis for the beginning of judgment
  • Suppose the lower left corner selected as the basis for judgment, an integer value greater than the lower left corner of the input, continue right judgment, less than one, then moved upwardly, then continues to determine

Code

function Find(target, array) {
    let len = array.length-1; //数组的行数
    let lenCol = array[0].length-1; //数组的列数 
    if(target<array[0][0] || target>array[len][lenCol]){ //进行临界值判断
        return false;
    }
    let i=len; //最后一行
    let j=0; //第一列
    while(i>0 && j<lenCol){
        if(target>array[i][j]){
            j++;
        }
        if(target<array[i][j]){
            i--;
        }
        if(target === array[i][j]){
            return true
        }
    }
    return false;

}

Guess you like

Origin www.cnblogs.com/kbinblog/p/11541765.html