Skip to content

Commit f330cc1

Browse files
committed
add set matrix zeroes solution
1 parent c65779b commit f330cc1

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

โ€Žset-matrix-zeroes/Tessa1217.java

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
import java.util.Arrays;
2+
3+
/**
4+
* m x n ํ–‰๋ ฌ matrix๊ฐ€ ์ฃผ์–ด์งˆ ๋•Œ, ์š”์†Œ๊ฐ€ 0์ด๋ผ๋ฉด 0์„ ํฌํ•จํ•˜๋Š” ํ•ด๋‹น ์š”์†Œ๋ฅผ ํฌํ•จํ•˜๋Š” ์ „์ฒด ํ–‰๊ณผ ์—ด์„
5+
* 0์œผ๋กœ ์„ธํŒ…ํ•˜์„ธ์š”.
6+
*/
7+
class Solution {
8+
9+
// Follow Up : ๊ณต๊ฐ„ ๋ณต์žก๋„ ๊ฐœ์„  ํ•„์š”
10+
// mark first row and column as marker to set 0's
11+
// ์‹œ๊ฐ„๋ณต์žก๋„: O(m * n), ๊ณต๊ฐ„๋ณต์žก๋„: O(1)
12+
public void setZeroes(int[][] matrix) {
13+
14+
boolean firstZero = false;
15+
16+
for (int i = 0; i < matrix.length; i++) {
17+
for (int j = 0; j < matrix[0].length; j++) {
18+
if (matrix[i][j] == 0) {
19+
matrix[i][0] = 0;
20+
if (j == 0) {
21+
firstZero = true;
22+
} else {
23+
matrix[0][j] = 0;
24+
}
25+
}
26+
}
27+
}
28+
29+
for (int i = 1; i < matrix.length; i++) {
30+
for (int j = 1; j < matrix[0].length; j++) {
31+
if (matrix[i][0] == 0 || matrix[0][j] == 0) {
32+
matrix[i][j] = 0;
33+
}
34+
}
35+
}
36+
37+
if (matrix[0][0] == 0) {
38+
Arrays.fill(matrix[0], 0);
39+
}
40+
41+
if (firstZero) {
42+
for (int i = 0; i < matrix.length; i++) {
43+
matrix[i][0] = 0;
44+
}
45+
}
46+
}
47+
48+
// ์‹œ๊ฐ„๋ณต์žก๋„: O (m * n), ๊ณต๊ฐ„๋ณต์žก๋„: O(m + n)
49+
// public void setZeroes(int[][] matrix) {
50+
51+
// // 0์„ ํฌํ•จํ•˜๋Š” ํ–‰๊ณผ ์—ด์˜ ์œ„์น˜ ์ €์žฅ
52+
// Set<Integer> rowsContainZeros = new HashSet<>();
53+
// Set<Integer> colsContainZeros = new HashSet<>();
54+
55+
// for (int i = 0; i < matrix.length; i++) {
56+
// for (int j = 0; j < matrix[0].length; j++) {
57+
// if (matrix[i][j] == 0) {
58+
// rowsContainZeros.add(i);
59+
// colsContainZeros.add(j);
60+
// }
61+
// }
62+
// }
63+
64+
// for (int row : rowsContainZeros) {
65+
// for (int j = 0; j < matrix[0].length; j++) {
66+
// matrix[row][j] = 0;
67+
// }
68+
// }
69+
70+
// for (int col : colsContainZeros) {
71+
// for (int i = 0; i < matrix.length; i++) {
72+
// matrix[i][col] = 0;
73+
// }
74+
// }
75+
// }
76+
77+
78+
}
79+

0 commit comments

Comments
ย (0)