挑战LeetCode热题100(TS版本)打卡第十天

63 阅读2分钟

挑战LeetCode热题100(TS版本)

打卡第十天

不求甚解

题型: 矩阵-二维数组

矩阵置零

给定一个 m x n 的矩阵,如果一个元素为 0 ,则将其所在行和列的所有元素都设为 0 。请使用 原地 算法

示例 1:

输入: matrix = [[1,1,1],[1,0,1],[1,1,1]]
输出: [[1,0,1],[0,0,0],[1,0,1]]

示例 2:

输入: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
输出: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]

思路:数组标记

1、我们可以用两个数组来反映出整个矩阵的状态,比如A数组用来反映矩阵的行信息,B数组用来反映矩阵的列信息,初始时两个数组元素值都为false。遍历矩阵数组的每一项,如果当前遍历先项是0,可以在将该项的行标和列标分别在A、B数组中标签为true。接下来我们只需要第二次遍历矩阵,查到的当前位置的行信息或列信息是不是true,如果有一项是true,意味着当前项的位置是0;

2、时间复杂度是O(mn),空间复杂度是O(m+n)

    /**
 Do not return anything, modify matrix in-place instead.
 */
function setZeroes(matrix: number[][]): void {
    // 两个数组来标记
    const m = matrix.length
    const n = matrix[0].length
    // const ml = new Array(m).fill(false)
    // const nl = new Array(n).fill(false)

    // for(let i=0;i<m;i++) {
    //     for(let j=0;j<n;j++) {
    //         if(matrix[i][j] === 0) {
    //             ml[i] = nl[j] = true
    //         }
    //     }
    // }

    // for(let i=0;i<m;i++) {
    //     for(let j=0;j<n;j++) {
    //         if(ml[i] || nl[j]) {
    //             matrix[i][j] = 0
    //         }
    //     }
    // }
};

进阶:

上述解法还可以通过其他方式来降低空间复杂度。我们可以通过把矩阵的第一项和矩阵的第一列设置为两个数组,需要注意的是,我们还需要两个额外的变量来记录第一行中是否含有0,第一列中是否含有0;

空间复杂度是:O(1),时间复杂度是 O(mn)

    /**
 Do not return anything, modify matrix in-place instead.
 */
function setZeroes(matrix: number[][]): void {
    const m = matrix.length
    let mR = false
    let nR = false
    
    for(let i=0;i<m;i++) {
        if( matrix[i][0] === 0) {
            mR = true
        }
    }

    for(let i=0;i<n;i++) {
        if( matrix[0][i] === 0) {
            nR = true
        }
    }

    for(let i=1;i<m;i++) {
        for(let j=0;j<n;j++) {
            if(matrix[i][j] === 0) {
                matrix[i][0] = 0
                matrix[0][j] = 0
            }
        }
    }

    for(let i=1;i<m;i++) {
        for(let j=1;j<n;j++) {
            if(matrix[i][0] === 0 ||  matrix[0][j] === 0) {
               matrix[i][j] = 0
            }
        }
    }

    if(mR) {
        for(let i=0;i<m;i++) {
            matrix[i][0] = 0
        }
    }

    if(nR) {
        for(let j=0;j<n;j++) {
            matrix[0][j] = 0
        }
    }
};