Skip to content

Commit e3095bb

Browse files
week14 mission merge-k-sorted-lists
1 parent a118c1d commit e3095bb

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
- 문제: https://leetcode.com/problems/merge-k-sorted-lists/
2+
- 풀이: https://algorithm.jonghoonpark.com/2024/02/19/leetcode-23
3+
4+
## 풀이 1
5+
6+
listsλ₯Ό μˆœνšŒν•˜λ©΄μ„œ κ°€μž₯ μž‘μ€ 수λ₯Ό κ°€μ§„ λ…Έλ“œλ₯Ό μ°Ύκ³ , κ·Έ λ…Έλ“œλ₯Ό mergedList 에 μΆ”κ°€ν•œλ‹€.
7+
8+
```java
9+
class Solution {
10+
public ListNode mergeKLists(ListNode[] lists) {
11+
ListNode mergedList = new ListNode();
12+
13+
ListNode current = mergedList;
14+
15+
while (true) {
16+
boolean done = true;
17+
int minIndex = 0;
18+
int currentMin = Integer.MAX_VALUE;
19+
20+
for (int i = 0; i < lists.length; i++) {
21+
ListNode node = lists[i];
22+
if (node == null) {
23+
continue;
24+
}
25+
26+
if (node.val < currentMin) {
27+
minIndex = i;
28+
currentMin = node.val;
29+
done = false;
30+
}
31+
}
32+
33+
if (done) {
34+
break;
35+
}
36+
37+
current.next = lists[minIndex];
38+
lists[minIndex] = lists[minIndex].next;
39+
40+
current = current.next;
41+
}
42+
43+
return mergedList.next;
44+
}
45+
}
46+
```
47+
48+
### TC, SC
49+
50+
λ¬Έμ œμ—μ„œ λ‹€μŒκ³Ό 같이 μ •μ˜κ°€ λ˜μ–΄μžˆλ‹€.
51+
52+
```
53+
k == lists.length
54+
```
55+
56+
μΆ”κ°€μ μœΌλ‘œ n을 list λ“€μ˜ item 수의 총합 이라고 μ •μ˜ν•˜μ˜€μ„ λ•Œ
57+
58+
μ‹œκ°„λ³΅μž‘λ„λŠ” `O(n * k)`, κ³΅κ°„λ³΅μž‘λ„λŠ” `O(n)` 이닀.
59+
60+
## 풀이 2: stream μ‚¬μš©ν•΄μ„œ ν’€κΈ°
61+
62+
μš°μ„  λ‹€ ν•˜λ‚˜μ˜ λ¦¬μŠ€νŠΈμ— ν•©μΉœ ν›„ μ •λ ¬ν•œλ‹€.
63+
64+
```java
65+
class Solution {
66+
public ListNode mergeKLists(ListNode[] lists) {
67+
List<ListNode> mergedListNode = new ArrayList<>();
68+
for (ListNode listNode : lists) {
69+
ListNode current = listNode;
70+
while (current != null) {
71+
mergedListNode.add(current);
72+
current = current.next;
73+
}
74+
}
75+
76+
ListNode listNode = new ListNode();
77+
final ListNode[] current = {listNode};
78+
mergedListNode.stream().sorted(Comparator.comparingInt(node -> node.val))
79+
.forEach(node -> {
80+
current[0].next = node;
81+
current[0] = current[0].next;
82+
});
83+
84+
return listNode.next;
85+
}
86+
}
87+
```
88+
89+
μ˜ˆμƒκ³ΌλŠ” λ‹€λ₯΄κ²Œ 였히렀 이 방식이 더 적은 μ‹€ν–‰μ‹œκ°„μœΌλ‘œ μ™„λ£Œλ˜μ—ˆλ‹€.
90+
91+
### TC, SC
92+
93+
n을 list λ“€μ˜ item 수의 총합 이라고 μ •μ˜ν•˜μ˜€μ„ λ•Œ, μ‹œκ°„λ³΅μž‘λ„λŠ” `O(nlogn)`, κ³΅κ°„λ³΅μž‘λ„λŠ” `O(n)` 이닀.

0 commit comments

Comments
Β (0)