File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ /**
3
+ 1. understanding
4
+ - iterate over all cells, if value is 0, then add row and col to sweep target set.
5
+ - for each row target set, and col target set, sweep all it's value to 0
6
+ 2. complexity
7
+ - time: O(m * n)
8
+ - space: O(m + n)
9
+ */
10
+ public void setZeroes (int [][] matrix ) {
11
+ Set <Integer > rows = new HashSet <>(); // O(m)
12
+ Set <Integer > cols = new HashSet <>(); // O(n)
13
+
14
+ for (int row = 0 ; row < matrix .length ; row ++) { // O(m)
15
+ for (int col = 0 ; col < matrix [row ].length ; col ++) { // O(n)
16
+ if (matrix [row ][col ] == 0 ) { // O(m * n)
17
+ rows .add (row );
18
+ cols .add (col );
19
+ }
20
+ }
21
+ }
22
+
23
+ for (int row : rows ) { // O(m)
24
+ int col = 0 ;
25
+ while (col < matrix [row ].length ) { // O(n)
26
+ matrix [row ][col ] = 0 ;
27
+ col ++;
28
+ }
29
+ }
30
+
31
+ for (int col : cols ) { // O(n)
32
+ int row = 0 ;
33
+ while (row < matrix .length ) { // O(m)
34
+ matrix [row ][col ] = 0 ;
35
+ row ++;
36
+ }
37
+ }
38
+ }
39
+ }
40
+
You can’t perform that action at this time.
0 commit comments