//优先队列
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
map<int, int> freq; //元素,频率
for (auto l:lists){
while(l){
freq[l->val]++;
l = l->next;
}
}
//频率,元素
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
for (auto f:freq) pq.push(make_pair(f.first, f.second));
ListNode* head = NULL;
ListNode* curNode = head;
while (!pq.empty()){
for (int i=1; i<=pq.top().second; i++){
if (!head) {
head = new ListNode(pq.top().first);
curNode = head;
}
else {
curNode->next = new ListNode(pq.top().first);
curNode = curNode->next;
}
}
pq.pop();
}
return head;
}
};