Skip to content

Commit 71d1d45

Browse files
73. Set Matrix Zeroes
Diffculty: Medium 159 / 159 test cases passed. Runtime: 128 ms Memory Usage: 14.2 MB
1 parent b49df0c commit 71d1d45

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

Medium/73.SetMatrixZeroes.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
"""
2+
Given a m x n matrix, if an element is 0, set its entire row and column
3+
to 0. Do it in-place.
4+
5+
Example:
6+
Input:
7+
[
8+
[0,1,2,0],
9+
[3,4,5,2],
10+
[1,3,1,5]
11+
]
12+
Output:
13+
[
14+
[0,0,0,0],
15+
[0,4,5,0],
16+
[0,3,1,0]
17+
]
18+
Follow up:
19+
- A straight forward solution using O(mn) space is probably a bad idea.
20+
- A simple improvement uses O(m + n) space, but still not the best
21+
solution.
22+
- Could you devise a constant space solution?
23+
"""
24+
#Diffculty: Medium
25+
#159 / 159 test cases passed.
26+
#Runtime: 128 ms
27+
#Memory Usage: 14.2 MB
28+
29+
#Runtime: 128 ms, faster than 98.17% of Python3 online submissions for Set Matrix Zeroes.
30+
#Memory Usage: 14.2 MB, less than 66.80% of Python3 online submissions for Set Matrix Zeroes.
31+
32+
class Solution:
33+
def setZeroes(self, matrix: List[List[int]]) -> None:
34+
"""
35+
Do not return anything, modify matrix in-place instead.
36+
"""
37+
row_size = len(matrix[0])
38+
col_size = len(matrix)
39+
rows_to_zero = set()
40+
cols_to_zero = set()
41+
for i in range(col_size):
42+
for j in range(row_size):
43+
if matrix[i][j] == 0:
44+
rows_to_zero.add(i)
45+
cols_to_zero.add(j)
46+
for i in range(col_size):
47+
if i in rows_to_zero:
48+
matrix[i] = [0] * row_size
49+
for j in cols_to_zero:
50+
matrix[i][j] = 0

0 commit comments

Comments
 (0)