算法(TS):搜索二维矩阵 II

编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性:

  • 每行的元素从左到右升序排列。
  • 每列的元素从上到下升序排列。

输入: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小,行尾比target大,则target可能在本行,其余情况均不在本行

ts 复制代码
function searchMatrix(matrix: number[][], target: number): boolean {
    const colTotal = matrix[0].length
    let isExist = false;
    for (const row of matrix) {
        const head = row[0]
        const tail = row[colTotal -1]
        if (head === target || tail === target) {
            isExist = true
            break
        }

        if (head < target && tail > target) {
            // 遍历本行
            isExist = row.indexOf(target) > -1
            if (isExist) {
                break
            }
        }
    }

    return isExist
};

空间复杂度O(1),时间复杂度O(nlogn)

解法二

从右上角开始找,如果查找到的值小于 target,则往下找,如果查找到的值大于 target,则往左找

ts 复制代码
function searchMatrix(matrix: number[][], target: number): boolean {
    let rowIndex = 0
    let colIndex = matrix[0].length - 1
    let isExist = false
    while(colIndex >= 0 && rowIndex < matrix.length) {
        const current = matrix[rowIndex][colIndex]
        if (current === target) {
            isExist = true
            break
        }

        if (current < target) {
            rowIndex++
        } else {
            colIndex--
        }
    }

    return isExist
};

空间复杂度 O(1),时间复杂度O(n)

相关推荐
cpp_250112 分钟前
P10098 [ROIR 2023] 地铁建设 (Day 2)
数据结构·c++·算法·贪心·二分答案·洛谷题解
এ慕ོ冬℘゜1 小时前
深入 JavaScript BOM:掌握 window 对象的窗口控制魔法
开发语言·javascript·ecmascript
阳明山水1 小时前
TimesFM与Moirai MoE零样本预测解析
人工智能·深度学习·算法·机器学习·架构
铅笔侠_小龙虾1 小时前
Rust 学习(2)-变量、常量与 shadowing
学习·算法·rust
AI科技星1 小时前
基于全域数学公理体系的三元极值题最简求解法【乖乖数学】
线性代数·算法·游戏·决策树·机器学习·乖乖数学·全域数学
Highcharts2 小时前
Highcharts 矩形树图 Treemap 示列|2025年多层级出口商品结构可视化
javascript·数据可视化
大鱼>2 小时前
宠物异常行为预警系统:边缘计算与实时检测
人工智能·深度学习·算法·iot·宠物
大家的林语冰3 小时前
✌️ Deno 2.9 来了,ESM 直接导入 CSS,甚至能开发桌面应用?!
前端·javascript·node.js
apcipot_rain3 小时前
某双非机试真题
算法
米尔的可达鸭3 小时前
深入操作系统 Socket 底层:套接字控制块、FD映射、阻塞IO核心完整实现
arm开发·数据结构·websocket·网络协议·算法·架构·安全架构