Skip to content

Commit c17486d

Browse files
add post '(Leetcode) 73 - Set Matrix Zeroes 풀이'
1 parent 2ed35c8 commit c17486d

File tree

1 file changed

+118
-2
lines changed

1 file changed

+118
-2
lines changed

_posts/2024-02-16-leetcode-73.md

+118-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,20 @@
11
---
22
layout: post
3-
title: (Leetcode) 73 - Set Matrix Zeroes
3+
title: (Leetcode) 73 - Set Matrix Zeroes 풀이
44
categories: [스터디-알고리즘]
5-
tags: [파이썬, 알고리즘, python, algorithm, Leetcode]
5+
tags:
6+
[
7+
파이썬,
8+
알고리즘,
9+
python,
10+
algorithm,
11+
Leetcode,
12+
java,
13+
Array,
14+
Hash Table,
15+
Matrix,
16+
in place,
17+
]
618
date: 2024-02-16 22:00:00 +0900
719
---
820

@@ -38,3 +50,107 @@ class Solution:
3850
for y in range(0, m):
3951
matrix[y][j] = 0
4052
```
53+
54+
## 자바로 다시 풀기 (24.07.31)
55+
56+
### 처음 생각난 방법
57+
58+
```java
59+
class Solution {
60+
public void setZeroes(int[][] matrix) {
61+
List<Index> indexOfZero = new ArrayList<>();
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+
indexOfZero.add(new Index(i, j));
67+
}
68+
}
69+
}
70+
71+
for (Index index : indexOfZero) {
72+
// update row
73+
Arrays.fill(matrix[index.i], 0);
74+
75+
// update column
76+
for (int i = 0; i < matrix.length; i++) {
77+
matrix[i][index.j] = 0;
78+
}
79+
}
80+
}
81+
}
82+
83+
class Index {
84+
int i;
85+
int j;
86+
87+
public Index(int i, int j) {
88+
this.i = i;
89+
this.j = j;
90+
}
91+
}
92+
```
93+
94+
#### TC, SC
95+
96+
문제에서 m과 n이 다음과 같이 정의되어 있다.
97+
98+
```
99+
m == matrix.length
100+
n == matrix[0].length
101+
```
102+
103+
시간복잡도는 `O(n * m)` 공간복잡도는 `O(n * m)` 이다.
104+
105+
### in place 방식으로 접근해보기
106+
107+
문제를 자세히 읽어보면 [in place](https://en.wikipedia.org/wiki/In-place_algorithm) 방식으로 풀라고 되어있다. 추가적인 공간을 사용하면 안된다. 그래서 다음과 같이 바꿔보았다. 컨셉은 첫번째 풀이와 동일하다.
108+
109+
행렬의 값은 `-231 <= matrix[i][j] <= 231 - 1` 으로 정의 되어 있다. 따라서 값을 변경해서 이미 진행된 값인지 표시하는 것은 불가능 하다.
110+
111+
어떤 행과 열이 0으로 바뀔지만 기록해둔다면 이전보다는 공간을 절약할 수 있다.
112+
113+
```java
114+
class Solution {
115+
public void setZeroes(int[][] matrix) {
116+
int[] row = new int[matrix.length];
117+
int[] col = new int[matrix[0].length];
118+
119+
for (int i = 0; i < matrix.length; i++) {
120+
for (int j = 0; j < matrix[0].length; j++) {
121+
if (matrix[i][j] == 0) {
122+
row[i] = 1;
123+
col[j] = 1;
124+
}
125+
}
126+
}
127+
128+
// update row
129+
for (int i = 0; i < row.length; i++) {
130+
if (row[i] == 1) {
131+
Arrays.fill(matrix[i], 0);
132+
}
133+
}
134+
135+
// update column
136+
for (int j = 0; j < col.length; j++) {
137+
if (col[j] == 1) {
138+
for (int i = 0; i < matrix.length; i++) {
139+
matrix[i][j] = 0;
140+
}
141+
}
142+
}
143+
}
144+
}
145+
```
146+
147+
#### TC, SC
148+
149+
문제에서 m과 n이 다음과 같이 정의되어 있다.
150+
151+
```
152+
m == matrix.length
153+
n == matrix[0].length
154+
```
155+
156+
시간복잡도는 `O(n * m)` 공간복잡도는 `O(n + m)` 이다. 공간 복잡도가 개선되었다.

0 commit comments

Comments
 (0)