当前位置: 代码迷 >> 综合 >> 数组操作:73. 矩阵置零
  详细解决方案

数组操作:73. 矩阵置零

热度:84   发布时间:2024-03-09 19:48:38.0

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

示例 1:

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

 

我们扫描一遍原始矩阵,找到所有为零的元素。
如果我们找到 [i, j] 的元素值为零,我们需要记录下行号 i 和列号 j。
用两个 sets ,一个记录行信息一个记录列信息。

if cell[i][j] == 0 {
    row_set.add(i)
    column_set.add(j)
}
最后,我们迭代原始矩阵,对于每个格子检查行 r 和列 c 是否被标记过,如果是就将矩阵格子的值设为 0。

if r in row_set or c in column_set {
    cell[r][c] = 0
}

 

class Solution {public void setZeroes(int[][] matrix) {int R = matrix.length;int C = matrix[0].length;Set<Integer> rows = new HashSet<Integer>();Set<Integer> cols = new HashSet<Integer>();// Essentially, we mark the rows and columns that are to be made zerofor (int i = 0; i < R; i++) {for (int j = 0; j < C; j++) {if (matrix[i][j] == 0) {rows.add(i);cols.add(j);}}}// Iterate over the array once again and using the rows and cols sets, update the elements.for (int i = 0; i < R; i++) {for (int j = 0; j < C; j++) {if (rows.contains(i) || cols.contains(j)) {matrix[i][j] = 0;}}}}
}

 

  相关解决方案