File tree 1 file changed +50
-0
lines changed
1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments