1
1
// m: height of matrix, n: width of matrix
2
2
// Time complexity: O(m*n)
3
- // Space complexity: O(m+n )
3
+ // Space complexity: O(1 )
4
4
5
5
/**
6
6
* @param {number[][] } matrix
@@ -10,27 +10,60 @@ var setZeroes = function (matrix) {
10
10
const h = matrix . length ;
11
11
const w = matrix [ 0 ] . length ;
12
12
13
- const setY = new Set ( ) ;
14
- const setX = new Set ( ) ;
13
+ // a flag for iterating rows of the first column
14
+ let temp1 = false ;
15
+
16
+ // a flag for iterating cols of the first row
17
+ let temp2 = false ;
15
18
16
19
for ( let i = 0 ; i < h ; i ++ ) {
17
- for ( let j = 0 ; j < w ; j ++ ) {
20
+ if ( matrix [ i ] [ 0 ] === 0 ) {
21
+ temp1 = true ;
22
+ break ;
23
+ }
24
+ }
25
+
26
+ for ( let i = 0 ; i < w ; i ++ ) {
27
+ if ( matrix [ 0 ] [ i ] === 0 ) {
28
+ temp2 = true ;
29
+ break ;
30
+ }
31
+ }
32
+
33
+ for ( let i = 1 ; i < h ; i ++ ) {
34
+ for ( let j = 1 ; j < w ; j ++ ) {
18
35
if ( matrix [ i ] [ j ] === 0 ) {
19
- setY . add ( i ) ;
20
- setX . add ( j ) ;
36
+ matrix [ i ] [ 0 ] = 0 ;
37
+ matrix [ 0 ] [ j ] = 0 ;
21
38
}
22
39
}
23
40
}
24
41
25
- for ( const y of setY ) {
26
- for ( let x = 0 ; x < w ; x ++ ) {
27
- matrix [ y ] [ x ] = 0 ;
42
+ for ( let i = 1 ; i < h ; i ++ ) {
43
+ if ( matrix [ i ] [ 0 ] === 0 ) {
44
+ for ( let j = 1 ; j < w ; j ++ ) {
45
+ matrix [ i ] [ j ] = 0 ;
46
+ }
28
47
}
29
48
}
30
49
31
- for ( const x of setX ) {
32
- for ( let y = 0 ; y < h ; y ++ ) {
33
- matrix [ y ] [ x ] = 0 ;
50
+ for ( let i = 1 ; i < w ; i ++ ) {
51
+ if ( matrix [ 0 ] [ i ] === 0 ) {
52
+ for ( let j = 1 ; j < h ; j ++ ) {
53
+ matrix [ j ] [ i ] = 0 ;
54
+ }
55
+ }
56
+ }
57
+
58
+ if ( temp1 ) {
59
+ for ( let i = 0 ; i < h ; i ++ ) {
60
+ matrix [ i ] [ 0 ] = 0 ;
61
+ }
62
+ }
63
+
64
+ if ( temp2 ) {
65
+ for ( let j = 0 ; j < w ; j ++ ) {
66
+ matrix [ 0 ] [ j ] = 0 ;
34
67
}
35
68
}
36
69
} ;
0 commit comments