Skip to content

Commit 8b08f9c

Browse files
committed
Time: 56 ms (37.91%), Space: 13.6 MB (39.50%) - LeetHub
1 parent 142e008 commit 8b08f9c

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
typedef pair<int, ListNode*> pil;
12+
class Solution {
13+
public:
14+
ListNode* mergeKLists(vector<ListNode*>& lists) {
15+
priority_queue<pil, vector<pil>, greater<pil>> pq;// min-heap
16+
int k = lists.size();
17+
18+
for (int i = 0; i < k; i++) {
19+
if(lists[i] != NULL)
20+
pq.push({lists[i]->val, lists[i]});
21+
}
22+
23+
ListNode* dummy = new ListNode(0);
24+
ListNode* curr = dummy;
25+
26+
while (!pq.empty()) {
27+
auto top = pq.top();
28+
pq.pop();
29+
30+
// dummy updt
31+
curr->next = top.second;
32+
curr = curr->next;
33+
34+
// pq updt
35+
if (top.second->next != NULL)
36+
pq.push({top.second->next->val, top.second->next});
37+
}
38+
39+
return dummy->next;
40+
}
41+
};

0 commit comments

Comments
 (0)