LeetCode刷题实战73:矩阵置零
共 5767字,需浏览 12分钟
·
2020-10-25 02:31
算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 矩阵置零,我们先来看题面:
https://leetcode-cn.com/problems/set-matrix-zeroes/
Given an m x n matrix. If an element is 0, set its entire row and column to 0. Do it in-place.
Follow up:
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?
题意
示例 1:
输入:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
输出:
[
[1,0,1],
[0,0,0],
[1,0,1]
]
示例 2:
输入:
[
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
输出:
[
[0,0,0,0],
[0,4,5,0],
[0,3,1,0]
]
解题
近在眼前的解法原来是坑
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
if n == 0:
return
m = len(matrix[0])
for i in range(n):
for j in range(m):
# 当我们找到为0的位置之后,将所在的行和列置为0
if matrix[i][j] == 0:
for k in range(m):
matrix[i][k] = 0
for k in range(n):
matrix[k][j] = 0
刚不过去只能绕
进阶解法
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
if n == 0:
return
m = len(matrix[0])
rows = [0 for _ in range(n)]
cols = [0 for _ in range(m)]
# 记录置为0的行和列
for i in range(n):
for j in range(m):
if matrix[i][j] == 0:
rows[i], cols[j] = 1, 1
# 如果所在行或者列置为0,那么当前位置为0
for i in range(n):
for j in range(m):
if rows[i] or cols[j]:
matrix[i][j] = 0
终极解法
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
if n == 0:
return
m = len(matrix[0])
row, col = False, False
# 特判0,0的位置
if matrix[0][0] == 0:
row, col = True, True
# 特判第0列是否含0
for i in range(n):
if matrix[i][0] == 0:
col = True
break
# 特判第0行是否含0
for i in range(m):
if matrix[0][i] == 0:
row = True
break
# 将i行,j列是否为0的信息存入matrix当中
for i in range(0, n):
for j in range(0, m):
if matrix[i][j] == 0:
matrix[i][0] = 0
matrix[0][j] = 0
for i in range(1, n):
for j in range(1, m):
# 根据第0行与第0列数据还原
if matrix[i][0] == 0 or matrix[0][j] == 0:
matrix[i][j] = 0
# 最后处理第0行与第0列
if row:
for i in range(m):
matrix[0][i] = 0
if col:
for i in range(n):
matrix[i][0] = 0
总结
上期推文: