js剑指 Offer 04. 二维数组中的查找

在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个高效的函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

示例:
现有矩阵 matrix 如下:

[
  [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]
]

给定 target = 5,返回 true。

给定 target = 20,返回 false。

思路:找到数组中最小的和最大的和target进行比较,若target在他们中间就循环比对。效率不行。

/**
 * @param {number[][]} matrix
 * @param {number} target
 * @return {boolean}
 */
var findNumberIn2DArray = function(matrix, target) {
    
    
    const outLength = matrix.length;
    if(outLength === 0){
    
    
        return false;
    }
    const inLength = matrix[0].length;
    for(let i = 0 ; i < outLength; i++){
    
    
        let min = matrix[i][0];
        let max = matrix[i][inLength-1];
        if(min === target || max === target){
    
    
            return true;
        }
        if(min < target && target < max){
    
    
            for(let j = 1; j < inLength-1;j++){
    
    
                if(target === matrix[i][j]){
    
    
                    return true;
                }
            }
        }
        if(target < min || target > max){
    
    
            continue;
        }
    }
    return false;
};

官方题解:

在这里插入图片描述

由于左上角和右上角是最小的数字和最大的数字,若target小于或者大于这两个数字可以直接返回false。

然后从左下角开始,进行比对。

/**
 * @param {number[][]} matrix
 * @param {number} target
 * @return {boolean}
 */
var findNumberIn2DArray = function (matrix, target) {
    
    
    // 处理数组为空的或者长度为0的情况
    if (matrix === null || matrix.length === 0) {
    
    
        return false;
    }
    const outLength = matrix.length;
    const inLength = matrix[0].length;
    
    const min = matrix[0][0];
    // target比最小的小 大于最大的
    const max = matrix[outLength - 1][inLength - 1];
    if (target < min || target > max) {
    
    
        return false;
    }
    let inTemp = 0;
    let outTemp = outLength - 1;
    while ( inLength-1 >= inTemp && outTemp >= 0) {
    
    
       if(target > matrix[outTemp][inTemp]){
    
    
           inTemp++
       } else if(target < matrix[outTemp][inTemp]) {
    
    
           outTemp--;
       } else {
    
    
           return true;
       }
    }
    return false;
};

猜你喜欢

转载自blog.csdn.net/tscn1/article/details/114896533