Skip to content

Commit 925e4b5

Browse files
committed
#286 solution
1 parent 99b0c2f commit 925e4b5

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

merge-k-sorted-lists/sungjinwi.cpp

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/*
2+
풀이 :
3+
최소힙을 사용해서 풀이한다
4+
리스트의 각 맨앞 노드를 최소힙에 넣고 최소 값을 가진 노드를 dummy에 붙여나간 뒤 next를 다시 최소힙에 넣는 것을 반복
5+
6+
노드의 개수 : N, list의 개수 K
7+
8+
TC : O (N log K)
9+
K개의 크기를 가지는 최소 힙에 넣고 제거하는 시간 -> logK * 모든 노드에 대한 순회 N
10+
11+
SC : O (K)
12+
최소힙 크기는 K에 비례
13+
*/
14+
15+
#include <vector>
16+
#include <queue>
17+
18+
using namespace std;
19+
20+
/**
21+
* Definition for singly-linked list.
22+
* struct ListNode {
23+
* int val;
24+
* ListNode *next;
25+
* ListNode() : val(0), next(nullptr) {}
26+
* ListNode(int x) : val(x), next(nullptr) {}
27+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
28+
* };
29+
*/
30+
31+
struct cmp {
32+
bool operator()(const ListNode* a, const ListNode* b) {
33+
return a->val > b->val;
34+
}
35+
};
36+
37+
class Solution {
38+
public:
39+
ListNode* mergeKLists(vector<ListNode*>& lists) {
40+
priority_queue<ListNode*, vector<ListNode*>, cmp> pq;
41+
42+
for (auto list : lists) {
43+
if (list)
44+
pq.push(list);
45+
}
46+
47+
ListNode dummy, *tail = &dummy;
48+
49+
while (!pq.empty()) {
50+
ListNode* minNode = pq.top(); pq.pop();
51+
52+
if (minNode->next)
53+
pq.push(minNode->next);
54+
55+
tail->next = minNode;
56+
tail = minNode;
57+
}
58+
return dummy.next;
59+
}
60+
};

0 commit comments

Comments
 (0)