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

345 阅读1分钟

编写一个高效的算法来搜索 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可能在本行,其余情况均不在本行

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,则往左找

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)