题目
编写一种算法,若M × N矩阵中某个元素为0,则将其所在的行与列清零。
示例1:
输入:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
输出:
[
[1,0,1],
[0,0,0],
[1,0,1]
]
分析: 暴力解法,创建一个数组,存放矩阵中元素为0得坐标值,然后遍历,将该坐标的行列均置为0
方法1: 暴力解法
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])
zero_coord = list()
for i in range(M):
for j in range(N):
if matrix[i][j] == 0:
zero_coord.append((i, j))
for coord in zero_coord:
i, j = coord
for v in range(N):
matrix[i][v] = 0
for c in range(M):
matrix[c][j] = 0
方法2: 可以用矩阵的第一行和第一列分别记录该行或者该列是否有0的元素,然后创建两个变量用来记录第一行和第一列是否存在零元素,在矩阵更新时,基于第一行和第一列的记录信息更新其它行和列的元素,然后再根据两个变量的记录结果更新第一行和第一列的元素,此方法通过矩阵本身记录信息,空间复杂度为O(1)
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])
mark1 = False
mark2 = False
for i in range(M):
if matrix[i][0] == 0:
mark1 = True
for i in range(N):
if matrix[0][i] == 0:
mark2 = True
for i in range(M):
for j in range(N):
if matrix[i][j] == 0:
matrix[i][0] = matrix[0][j] = 0
for i in range(1, M):
for j in range(1, N):
if matrix[i][0] == 0 or matrix[0][j] == 0:
matrix[i][j] = 0
if mark1:
for i in range(M):
matrix[i][0] = 0
if mark2:
for i in range(N):
matrix[0][i] = 0