LC240 JS

127 阅读1分钟

题意

有一个矩阵,每一行,从左到右,数值从小到大,纵向亦然,给个值,返回矩阵中是否含有这个数值。有时间限制。

思路

取出rowMin、rowMax,colMin,colMax,在画出的小矩阵范围内搜索,会快些。
##代码

/**
 * @param {number[][]} matrix
 * @param {number} target
 * @return {boolean}
 */
var searchMatrix = function(matrix, target){
    if(matrix.length < 1){
        return false;
    }
    let width = matrix[0].length;
    let height = matrix.length;

    let rowMin = -1;
    if(matrix[0][width - 1] >= target){
        rowMin = 0;
    }
    else{
        while((++rowMin < height) && (matrix[rowMin][width - 1] < target));
        if(rowMin >= height){
            return false;
        }
    }

    let rowMax = height;
    if(matrix[height - 1][0] <= target){
        rowMax = height - 1;
    }
    else{
        while((--rowMax > 0) && (matrix[rowMax][0] > target));
        if(rowMax < 0){
            return false;
        }
    }

    let colMin = -1;
    if(matrix[height - 1][0] >= target){
        colMin = 0;
    }
    else{
        while((++colMin < width) && (matrix[height - 1][colMin] < target));
        if(colMin >= width){
            return false;
        }
    }

    let colMax = width;
    if(matrix[0][width - 1] <= target){
        colMax = width - 1;
    }
    else{
        while((--colMax > 0) && (matrix[0][colMax] > target));
        if(colMax < 0){
            return false;
        }
    }

    for(let i = rowMin; i <= rowMax; ++i){
        for(let j = colMin; j <= colMax; ++j){
            if(matrix[i][j] === target){
                return true;
            }
        }
    }
    return false;
};

ps

提交成功我去看了最佳答案,人家直接一个循环搞定了,- -