-
Notifications
You must be signed in to change notification settings - Fork 11
/
Day-559.cpp
38 lines (38 loc) · 1.11 KB
/
Day-559.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
/**
* 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) {
ListNode *res_head , *res_end;
res_head = res_end = nullptr;
set<pair<int, ListNode*>> h;
for (int i=0; i<lists.size(); ++i) {
if (lists[i] != nullptr) {
h.insert(make_pair(lists[i]->val , lists[i]));
}
}
while (!h.empty()) {
ListNode *temp = h.begin()->second;
if ( res_head == nullptr) {
res_head = temp;
res_end = temp;
} else {
res_end->next = temp;
res_end = res_end->next;
}
if (temp->next != nullptr) {
h.insert(make_pair(temp->next->val , temp->next));
}
h.erase(h.begin());
}
return res_head;
}
};