【矩阵】面试题 零矩阵
程序员文章站
2022-05-04 19:18:19
想要看更加舒服的排版、更加准时的推送关注公众号“不太灵光的程序员”每日八点有干货推送,微信随时解答你的疑问面试题 01.08 零矩阵 python3矩阵 中等编写一种算法,若M × N矩阵中某个元素为0,则将其所在的行与列清零。示例 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....
想要看更加舒服的排版、更加准时的推送
关注公众号“不太灵光的程序员”
每日八点有干货推送,微信随时解答你的疑问
面试题 01.08 零矩阵 python3
矩阵
中等
编写一种算法,若M × N矩阵中某个元素为0,则将其所在的行与列清零。
示例 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]
]
from typing import List
# 63%
# 执行用时:52 ms
# 内存消耗:14.1 MB
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])
temp = []
for i in range(m):
for j in range(n):
if matrix[i][j] == 0:
temp.append((i, j))
for i, j in temp:
for k in range(m):
matrix[k][j] = 0
for k in range(n):
matrix[i][k] = 0
# 98.4%
# 执行用时:40 ms
# 内存消耗:13.9 MB
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
if matrix:
m = len(matrix)
n = len(matrix[0])
mi = set()
ni = set()
for i in range(m):
for j in range(n):
if matrix[i][j] == 0:
mi.add(i)
ni.add(j)
for i in mi:
for j in range(n):
matrix[i][j] = 0
for j in ni:
for i in range(m):
matrix[i][j] = 0
if __name__ == "__main__":
s = Solution()
m = [
[1, 1, 1],
[1, 0, 1],
[1, 1, 1]
]
s.setZeroes(m)
print(m)
m = [
[0, 1, 2, 0],
[3, 4, 5, 2],
[1, 3, 1, 5]
]
s.setZeroes(m)
print(m)
m = [
[0, 1, 2, 0, 1],
[3, 4, 0, 2, 1],
[1, 3, 1, 5, 1]
]
s.setZeroes(m)
print(m)
推荐阅读:
本文地址:https://blog.csdn.net/qq_23934063/article/details/107449662