73.矩阵置零
链接:73.矩阵置零
难度:Medium
标签:数组、哈希表、矩阵
简介:给定一个 m x n 的矩阵,如果一个元素为 0,则将其所在行和列的所有元素都设为 0。请使用原地算法。
题解 1 - typescript
- 编辑时间:2021-03-21
- 执行用时:116ms
- 内存消耗:41.2MB
- 编程语言:typescript
- 解法介绍:记录 col 要置零的下标。
function setZeroes(matrix: number[][]): void {
  const rowLen = matrix.length;
  const colLen = matrix[0].length;
  const colIndexSet = new Set<number>();
  for (let i = 0; i < rowLen; i++) {
    const row = matrix[i];
    let f = false;
    for (let j = 0; j < colLen; j++) {
      if (row[j] === 0) {
        f = true;
        colIndexSet.add(j);
      }
    }
    f && row.fill(0);
  }
  for (let i = 0; i < rowLen; i++) {
    for (const j of colIndexSet) {
      matrix[i][j] = 0;
    }
  }
}