思路
先获取元素为0所在的行和列,用集合rows 存放元素为0的行,集合cols存放元素为0的列
遍历矩阵,遇到的行、列为0元素所在行、列,将对应行、列的元素设置为0
ps:用集合可以去重、用in时时间复杂度O(1)
python
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
"""
rows=set()
cols=set()
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if matrix[i][j]==0:
rows.add(i)
cols.add(j)
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if i in rows:
matrix[i][j]=0
else:
if j in cols:
matrix[i][j]=0
return matrix