题目描述
思路分析
链表模拟
2个链表归并的扩展。其中求
k
k
k个点的
v
a
l
val
val的最小值用到了堆排序优化。
代码实现
/**
* 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:
struct cmp{
bool operator()(ListNode* a,ListNode* b){
return a->val>b->val;
}
};
ListNode* mergeKLists(vector<ListNode*>& lists) {
priority_queue<ListNode*,vector<ListNode*>,cmp> heap;
auto dummy=new ListNode(-1),tail=dummy;
for(auto l:lists)if(l) heap.push(l);
while(heap.size()){
auto t=heap.top();
heap.pop();
tail=tail->next=t;
if(t->next) heap.push(t->next);
}
return dummy->next;
}
};