Skip to content

Commit 6036c10

Browse files
week14 mission set-matrix-zeroes : add in place approach
1 parent 96980b9 commit 6036c10

File tree

1 file changed

+76
-3
lines changed

1 file changed

+76
-3
lines changed

โ€Žset-matrix-zeroes/dev-jonghoonpark.md

Lines changed: 76 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,9 +50,7 @@ n == matrix[0].length
5050

5151
์‹œ๊ฐ„๋ณต์žก๋„๋Š” `O(n * m)` ๊ณต๊ฐ„๋ณต์žก๋„๋Š” `O(n * m)` ์ด๋‹ค.
5252

53-
## in place ๋ฐฉ์‹์œผ๋กœ ์ ‘๊ทผํ•ด๋ณด๊ธฐ
54-
55-
๋ฌธ์ œ๋ฅผ ์ž์„ธํžˆ ์ฝ์–ด๋ณด๋ฉด [in place](https://en.wikipedia.org/wiki/In-place_algorithm) ๋ฐฉ์‹์œผ๋กœ ํ’€๋ผ๊ณ  ๋˜์–ด์žˆ๋‹ค.
53+
## simple improvement
5654

5755
```java
5856
class Solution {
@@ -98,3 +96,78 @@ n == matrix[0].length
9896
```
9997

10098
์‹œ๊ฐ„๋ณต์žก๋„๋Š” `O(n * m)` ๊ณต๊ฐ„๋ณต์žก๋„๋Š” `O(n + m)` ์ด๋‹ค. ๊ณต๊ฐ„ ๋ณต์žก๋„๊ฐ€ ๊ฐœ์„ ๋˜์—ˆ๋‹ค.
99+
100+
## in place ๋ฐฉ์‹์œผ๋กœ ์ ‘๊ทผํ•ด๋ณด๊ธฐ
101+
102+
๋ฌธ์ œ๋ฅผ ์ž์„ธํžˆ ์ฝ์–ด๋ณด๋ฉด [in place](https://en.wikipedia.org/wiki/In-place_algorithm) ๋ฐฉ์‹์œผ๋กœ ํ’€๋ผ๊ณ  ๋˜์–ด์žˆ๋‹ค.
103+
104+
```java
105+
class Solution {
106+
public void setZeroes(int[][] matrix) {
107+
boolean shouldUpdateFirstRow = false;
108+
boolean shouldUpdateFirstColumn = false;
109+
110+
for (int i = 0; i < matrix.length; i++) {
111+
if (matrix[i][0] == 0) {
112+
shouldUpdateFirstColumn = true;
113+
break;
114+
}
115+
}
116+
117+
for (int j = 0; j < matrix[0].length; j++) {
118+
if (matrix[0][j] == 0) {
119+
shouldUpdateFirstRow = true;
120+
break;
121+
}
122+
}
123+
124+
for (int i = 1; i < matrix.length; i++) {
125+
for (int j = 1; j < matrix[0].length; j++) {
126+
if (matrix[i][j] == 0) {
127+
matrix[i][0] = 0;
128+
matrix[0][j] = 0;
129+
}
130+
}
131+
}
132+
133+
// update row
134+
for (int i = 1; i < matrix.length; i++) {
135+
if (matrix[i][0] == 0) {
136+
Arrays.fill(matrix[i], 0);
137+
}
138+
}
139+
140+
// update column
141+
for (int j = 1; j < matrix[0].length; j++) {
142+
if (matrix[0][j] == 0) {
143+
for (int i = 0; i < matrix.length; i++) {
144+
matrix[i][j] = 0;
145+
}
146+
}
147+
}
148+
149+
// update first row if contains zero
150+
if (shouldUpdateFirstRow) {
151+
Arrays.fill(matrix[0], 0);
152+
}
153+
154+
// update first column if contains zero
155+
if (shouldUpdateFirstColumn) {
156+
for (int i = 0; i < matrix.length; i++) {
157+
matrix[i][0] = 0;
158+
}
159+
}
160+
}
161+
}
162+
```
163+
164+
#### TC, SC
165+
166+
๋ฌธ์ œ์—์„œ m๊ณผ n์ด ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ •์˜๋˜์–ด ์žˆ๋‹ค.
167+
168+
```
169+
m == matrix.length
170+
n == matrix[0].length
171+
```
172+
173+
์‹œ๊ฐ„๋ณต์žก๋„๋Š” `O(n * m)` ๊ณต๊ฐ„๋ณต์žก๋„๋Š” `O(1)` ์ด๋‹ค. ๊ณต๊ฐ„ ๋ณต์žก๋„๊ฐ€ ํ•œ ๋ฒˆ ๋” ๊ฐœ์„ ๋˜์—ˆ๋‹ค.

0 commit comments

Comments
ย (0)