73. Set Matrix Zeroes

Leetcode link

题目简介

/**
 * @param {number[][]} matrix
 * @return {void} Do not return anything, modify matrix in-place instead.
 */

题目给我们一个 m*n 的矩阵 matrix

要求我们把矩阵内元素值为 0 的行与列全部置 0

并且只能在原地操作 matrix

解题思路

我们首先遍历整个 matrix,找出需要置 0 的行与列

然后我们分别把对应的行与列置 0 即可

Javascript

/**
 * @param {number[][]} matrix
 * @return {void} Do not return anything, modify matrix in-place instead.
 */
var setZeroes = function (matrix) {
    const height = matrix.length
    const width = matrix[0].length
    const zeroRows = []
    const zeroCols = []

    for (let i = 0; i < height; i++) {
        for (let j = 0; j < width; j++) {
            if (matrix[i][j] === 0) {
                zeroRows.push(i)
                zeroCols.push(j)
            }
        }
    }

    zeroRows.forEach(row => {
        matrix[row].fill(0)
    })

    zeroCols.forEach(col => {
        for (let row = 0; row < height; row++) {
            matrix[row][col] = 0
        }
    })
};

results matching ""

    No results matching ""