-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathLC0023.cpp
More file actions
executable file
·49 lines (41 loc) · 978 Bytes
/
LC0023.cpp
File metadata and controls
executable file
·49 lines (41 loc) · 978 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*
Problem Statement: https://leetcode.com/problems/merge-k-sorted-lists/
Time: O(n • log k)
Space: O(n • k + k)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode *head, *curr;
head = curr = nullptr;
// helper function
auto compare = [](ListNode* l1, ListNode* l2) {
if (!l1)
return static_cast<bool>(l2);
else if (!l2)
return static_cast<bool>(l2);
else
return l1->val > l2->val;
};
priority_queue<ListNode*, vector<ListNode*>, decltype(compare)> pq(compare);
// initialization
for (ListNode* list: lists)
if (list)
pq.push(list);
// merge the k sorted lists
while (!pq.empty()) {
ListNode* list = pq.top();
pq.pop();
if (!head)
head = list;
if (curr)
curr->next = list;
curr = exchange(list, list->next);
curr->next = nullptr;
if (list)
pq.push(list);
}
return head;
}
};