力扣23. 合并K个升序链表
Posted 幽殇默
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了力扣23. 合并K个升序链表相关的知识,希望对你有一定的参考价值。
/**
* 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:
priority_queue<int, vector<int>, greater<int> > heap;
ListNode* mergeKLists(vector<ListNode*>& lists)
{
ListNode* head=new ListNode(-1);
ListNode* temp=head;
for(int i=0;i<lists.size();i++)
{
while(lists[i])
{
heap.push(lists[i]->val);
lists[i]=lists[i]->next;
}
}
while(heap.size())
{
temp=temp->next=new ListNode(heap.top());
heap.pop();
}
return head->next;
}
};
y总方法:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
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;
}
};
以上是关于力扣23. 合并K个升序链表的主要内容,如果未能解决你的问题,请参考以下文章