Skip to content

Commit 10b20a4

Browse files
committed
feat: solve set matrix zeroes
1 parent 8c03cfc commit 10b20a4

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

set-matrix-zeroes/GangBean.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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+

0 commit comments

Comments
 (0)