题解 | #二维数组中的查找#

二维数组中的查找

https://www.nowcoder.com/practice/abc3fe2ce8e146608e868a70efebf62e?tpId=295&tqId=23256&ru=%2Fpractice%2Fd3df40bd23594118b57554129cadf47b&qru=%2Fta%2Fformat-top101%2Fquestion-ranking&sourceUrl=%2Fexam%2Fcompany

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param target int整型 
 * @param array int整型二维数组 
 * @return bool布尔型
 */
function Find( target ,  array ) {
    // write code here
    if (!array || array.length === 0 || array[0].length === 0) {
        return false; // 空矩阵或空行或空列,返回false;
    }
    const rows = array.length;
    const cols = array[0].length;

    let row = 0;
    let col = cols - 1; // 从右上角开始搜索

    while (row < rows && col >= 0) {
        const currentVal = array[row][col];
        if (currentVal === target) {
            return true; // 找到目标值
        } else if (currentVal < target) {
            row++; // 当前值小于目标值,向下移动; 
                   // 因为是从右上角开始查找,目标值只可能在下方。
        } else {
            col--; // 当前值大于目标值,向左移动
        }
    }
    return false;
}
module.exports = {
    Find : Find
};

从右上角开始的策略,

在每次比较后排除一行或一列,以实现高效的查找。

如果当前值等于目标值,就返回 true,表示找到了目标值。

如果当前值小于目标值,就向下移动一行,因为目标值只可能在下方。(从右上角开始)

如果当前值大于目标值,就向左移动一列,因为目标值只可能在左侧。

这样,不断地缩小搜索范围,直到找到目标值或搜索范围为空,最后返回 false 表示未找到目标值。

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务