-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path23. Merge k Sorted Lists.cpp
47 lines (46 loc) · 1.53 KB
/
23. Merge k Sorted Lists.cpp
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
// sort the array of first elements first, remove smallest element and add its successor - multiset or set with custom comparator
multiset<int> mset;
unordered_map<int,vector<ListNode*>> hash;
for (auto i:lists) {
if (!i) continue;
mset.insert(i->val);
hash[i->val].push_back(i);
}
if (hash.empty()) return nullptr;
ListNode* head = hash[*mset.begin()].back();
ListNode* curr = head;
ListNode* nex;
hash[*mset.begin()].pop_back();
mset.erase(mset.begin());
if (head->next) {
mset.insert(head->next->val);
hash[head->next->val].push_back(head->next);
}
while (!mset.empty()) {
nex = hash[*mset.begin()].back();
curr->next = nex;
curr = nex;
// Remove smallest element
hash[*mset.begin()].pop_back();
mset.erase(mset.begin());
// Add the successor of smallest element
if (curr->next) {
mset.insert(curr->next->val);
hash[curr->next->val].push_back(curr->next);
}
}
return head;
}