原题
https://leetcode.cn/problems/set-matrix-zeroes/description/
思路
遍历
复杂度
时间:O(m * n)
空间:O(m * n)
Python代码
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
m = len(matrix)
n = len(matrix[0])
rows = set()
cols = set()
for i in range(m):
for j in range(n):
if matrix[i][j] == 0:
rows.add(i)
cols.add(j)
for r in rows:
matrix[r] = [0] * n
for c in cols:
for r in range(m):
matrix[r][c] = 0
Go代码
func setZeroes(matrix [][]int) {
m, n := len(matrix), len(matrix[0])
rows, cols := map[int]bool{}, map[int]bool{}
// 记录元素0所在的位置
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if matrix[i][j] == 0 {
rows[i] = true
cols[j] = true
}
}
}
for r := range rows {
matrix[r] = make([]int, n)
}
for c := range cols {
for r := 0; r < m; r++ {
matrix[r][c] = 0
}
}
}

被折叠的 条评论
为什么被折叠?



