File tree Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+
3
+ sol1 ) brute force
4
+ save zero points, replace row
5
+
6
+ read O(mn)
7
+ save zero points
8
+ replace row,cols
9
+ tc : O(mn)
10
+ sc : O(mn)
11
+
12
+ sol2) use bitwise
13
+ length of matrix < integer range
14
+ use bit wise
15
+ tc : O(mn)
16
+ sc : O(m + n)
17
+
18
+ sol3) use first row, col as memo
19
+ read matrix, check to row or col if zero
20
+
21
+ replace if row, col is marked as zero
22
+ tc : O(mn)
23
+ sc : O(1) in-place
24
+ */
25
+ class Solution {
26
+ public void setZeroes (int [][] matrix ) {
27
+ int m = matrix .length ;
28
+ int n = matrix [0 ].length ;
29
+ boolean firstRowZero = false ;
30
+ boolean firstColZero = false ;
31
+ for (int i = 0 ; i < m ; i ++) {
32
+ for (int j = 0 ; j < n ; j ++) {
33
+ if (matrix [i ][j ] == 0 ) {
34
+ if (i == 0 ) firstRowZero = true ;
35
+ if (j == 0 ) firstColZero = true ;
36
+ matrix [i ][0 ] = 0 ;
37
+ matrix [0 ][j ] = 0 ;
38
+ }
39
+ }
40
+ }
41
+ for (int i = 1 ; i <m ; i ++) {
42
+ for (int j = 1 ; j < n ; j ++) {
43
+ if (matrix [i ][0 ] == 0 || matrix [0 ][j ] == 0 ) {
44
+ matrix [i ][j ] = 0 ;
45
+ }
46
+ }
47
+ }
48
+ if (firstRowZero ) {
49
+ Arrays .fill (matrix [0 ], 0 );
50
+ }
51
+ if (firstColZero ) {
52
+ for (int j = 0 ; j <m ; j ++) {
53
+ matrix [j ][0 ] = 0 ;
54
+ }
55
+ }
56
+
57
+
58
+ }
59
+ }
You can’t perform that action at this time.
0 commit comments