73. 矩阵置零
代码
ts
/**
* 73. 矩阵置零
* https://leetcode.cn/problems/set-matrix-zeroes/
*/
/**
Do not return anything, modify matrix in-place instead.
*/
function setZeroes(matrix: number[][]): void {
const rows = new Set<number>();
const cols = new Set<number>();
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[0].length; j++) {
if (matrix[i][j] === 0) {
rows.add(i);
cols.add(j);
}
}
}
for (const row of rows) {
matrix[row].fill(0);
}
for (const col of cols) {
for (let row = 0; row < matrix.length; row++) {
matrix[row][col] = 0;
}
}
}思路
使用两个集合分别记录需要置零的行和列:
- 第一次遍历:遍历整个矩阵,将所有值为 0 的位置的行号和列号分别存入
rows和cols集合中 - 第二次遍历:遍历
rows集合,将对应的行全部置零 - 第三次遍历:遍历
cols集合,将对应的列全部置零
这样可以在不影响判断的情况下完成矩阵置零操作。
- 时间复杂度
,其中 为矩阵行数, 为矩阵列数 - 空间复杂度
,需要额外的集合存储行号和列号