给定一个 m x n 的矩阵,如果一个元素为 0,则将其所在行和列的所有元素都设为 0。请使用原地算法。
题目链接:https://leetcode-cn.com/problems/set-matrix-zeroes/
先发出自己的解法:
class Solution: def setZeroes(self, matrix): """ Do not return anything, modify matrix in-place instead. """ rowno = [] colno = [] row = 0 rowlen = 0 haszero = False for ilist in matrix: rowlen = len(ilist) for j in range(rowlen): if ilist[j] == 0: colno.append(j) haszero = True if haszero: rowno.append(row) haszero = False row += 1 for i in rowno: matrix[i] = [0]*rowlen colno = set(colno) for j in colno: for i in range(len(matrix)): if i not in set(rowno): for col in colno: matrix[i][col] = 0
这段代码执行效率还是慢。
提交之后找到一个效率高,并且很能直观理解的解法:
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
m,n = len(matrix), len(matrix[0])
for i in range(m):
for j in range(n):
if matrix[i][j] == 0:
for a in range(m):
if matrix[a][j]!= 0:
matrix[a][j] = 'checked'
for b in range(n):
if matrix[i][b]!=0:
matrix[i][b] = 'checked'
for i in range(m):
for j in range(n):
if matrix[i][j] == 'checked':
matrix[i][j] = 0