Skip to content

Commit 25f0136

Browse files
week14 mission set-matrix-zeroes
1 parent 0f20cf0 commit 25f0136

File tree

1 file changed

+100
-0
lines changed

1 file changed

+100
-0
lines changed
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
- ๋ฌธ์ œ: https://leetcode.com/problems/set-matrix-zeroes/
2+
- ํ’€์ด: https://algorithm.jonghoonpark.com/2024/02/16/leetcode-73
3+
4+
## ์ฒ˜์Œ ์ƒ๊ฐ๋‚œ ๋ฐฉ๋ฒ•
5+
6+
```java
7+
class Solution {
8+
public void setZeroes(int[][] matrix) {
9+
List<Index> indexOfZero = new ArrayList<>();
10+
11+
for (int i = 0; i < matrix.length; i++) {
12+
for (int j = 0; j < matrix[0].length; j++) {
13+
if (matrix[i][j] == 0) {
14+
indexOfZero.add(new Index(i, j));
15+
}
16+
}
17+
}
18+
19+
for (Index index : indexOfZero) {
20+
// update row
21+
Arrays.fill(matrix[index.i], 0);
22+
23+
// update column
24+
for (int i = 0; i < matrix.length; i++) {
25+
matrix[i][index.j] = 0;
26+
}
27+
}
28+
}
29+
}
30+
31+
class Index {
32+
int i;
33+
int j;
34+
35+
public Index(int i, int j) {
36+
this.i = i;
37+
this.j = j;
38+
}
39+
}
40+
```
41+
42+
### TC, SC
43+
44+
๋ฌธ์ œ์—์„œ m๊ณผ n์ด ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ •์˜๋˜์–ด ์žˆ๋‹ค.
45+
46+
```
47+
m == matrix.length
48+
n == matrix[0].length
49+
```
50+
51+
์‹œ๊ฐ„๋ณต์žก๋„๋Š” `O(n * m)` ๊ณต๊ฐ„๋ณต์žก๋„๋Š” `O(n * m)` ์ด๋‹ค.
52+
53+
## in place ๋ฐฉ์‹์œผ๋กœ ์ ‘๊ทผํ•ด๋ณด๊ธฐ
54+
55+
๋ฌธ์ œ๋ฅผ ์ž์„ธํžˆ ์ฝ์–ด๋ณด๋ฉด [in place](https://en.wikipedia.org/wiki/In-place_algorithm) ๋ฐฉ์‹์œผ๋กœ ํ’€๋ผ๊ณ  ๋˜์–ด์žˆ๋‹ค.
56+
57+
```java
58+
class Solution {
59+
public void setZeroes(int[][] matrix) {
60+
int[] row = new int[matrix.length];
61+
int[] col = new int[matrix[0].length];
62+
63+
for (int i = 0; i < matrix.length; i++) {
64+
for (int j = 0; j < matrix[0].length; j++) {
65+
if (matrix[i][j] == 0) {
66+
row[i] = 1;
67+
col[j] = 1;
68+
}
69+
}
70+
}
71+
72+
// update row
73+
for (int i = 0; i < row.length; i++) {
74+
if (row[i] == 1) {
75+
Arrays.fill(matrix[i], 0);
76+
}
77+
}
78+
79+
// update column
80+
for (int j = 0; j < col.length; j++) {
81+
if (col[j] == 1) {
82+
for (int i = 0; i < matrix.length; i++) {
83+
matrix[i][j] = 0;
84+
}
85+
}
86+
}
87+
}
88+
}
89+
```
90+
91+
#### TC, SC
92+
93+
๋ฌธ์ œ์—์„œ m๊ณผ n์ด ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ •์˜๋˜์–ด ์žˆ๋‹ค.
94+
95+
```
96+
m == matrix.length
97+
n == matrix[0].length
98+
```
99+
100+
์‹œ๊ฐ„๋ณต์žก๋„๋Š” `O(n * m)` ๊ณต๊ฐ„๋ณต์žก๋„๋Š” `O(n + m)` ์ด๋‹ค. ๊ณต๊ฐ„ ๋ณต์žก๋„๊ฐ€ ๊ฐœ์„ ๋˜์—ˆ๋‹ค.

0 commit comments

Comments
ย (0)