python
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
# 思路是1.记录每一个0元素的行和列下标 2.遍历全数组
row_index=[]
column_index=[]
m=len(matrix)
n=len(matrix[0])
# print(m,n)
for i in range(m):
for j in range(n):
if matrix[i][j]==0:
row_index.append(i)
column_index.append(j)
for i in range(m):
for j in range(n):
if(i in row_index or j in column_index):
matrix[i][j]=0
思路:
- 先扫一遍记录0
- 再扫一遍置0
- 时间复杂度就n*m太慢
- 空间复杂度是m+n
python
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
row = len(matrix)
col = len(matrix[0])
row0_flag = False
col0_flag = False
# 找第一行是否有0
for j in range(col):
if matrix[0][j] == 0:
row0_flag = True
break
# 第一列是否有0
for i in range(row):
if matrix[i][0] == 0:
col0_flag = True
break
# 把第一行或者第一列作为 标志位
for i in range(1, row):
for j in range(1, col):
if matrix[i][j] == 0:
matrix[i][0] = matrix[0][j] = 0
#print(matrix)
# 置0
for i in range(1, row):
for j in range(1, col):
if matrix[i][0] == 0 or matrix[0][j] == 0:
matrix[i][j] = 0
if row0_flag:
for j in range(col):
matrix[0][j] = 0
if col0_flag:
for i in range(row):
matrix[i][0] = 0
思路:
- 先记录第一行第一列有无0
- 把第一行第一列作为标志位
- 空间变成o(1)
- 时间还是o(n*m)