赞
踩
难度中等528收藏分享切换为英文接收动态反馈
给定一个 *m* x *n*
的矩阵,如果一个元素为 0 ,则将其所在行和列的所有元素都设为 0 。请使用 原地 算法**。**
进阶:
O(*m**n*)
的额外空间,但这并不是一个好的解决方案。O(*m* + *n*)
的额外空间,但这仍然不是最好的解决方案。示例 1:
输入:matrix = [[1,1,1],[1,0,1],[1,1,1]]
输出:[[1,0,1],[0,0,0],[1,0,1]]
示例 2:
输入:matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
输出:[[0,0,0,0],[0,4,5,0],[0,3,1,0]]
提示:
m == matrix.length
n == matrix[0].length
1 <= m, n <= 200
-231 <= matrix[i][j] <= 231 - 1
解法一:暴力
class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ cnt = [] m,n = len(matrix),len(matrix[0]) for i in range(m): for j in range(n): if matrix[i][j] == 0: cnt.append([i,j]) for row,col in cnt: for i in range(m): matrix[i][col] = 0 for j in range(n): matrix[row][j] = 0
解法二:状态压缩
class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ rowFlag = 0 colFlag = 0 m,n = len(matrix),len(matrix[0]) for i in range(m): if matrix[i][0] == 0: colFlag = 1 break for j in range(n): if matrix[0][j] == 0: rowFlag = 1 break for i in range(1,m): for j in range(1,n): if matrix[i][j] == 0: matrix[i][0] = 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 rowFlag == 1: for j in range(n): matrix[0][j] = 0 if colFlag == 1: for i in range(m): matrix[i][0] = 0
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。