第四天leetcode刷题
解题思路:运用最小堆,先去每个链表的第一个元素构建最小堆,由于链表都是已排序的,因此,每次堆的顶部都是最小的元素,这里用优先队列实现最小堆。
具体代码实现如下:
/**
* 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) const
{
return a ->val > b ->val;
}
};
ListNode* mergeKLists(vector<ListNode*>& lists) {
priority_queue<ListNode*,vector<ListNode*>,cmp> pq;
ListNode* ret = nullptr;
ListNode* current = nullptr;
for(int i = 0;i < lists.size();++i)
if(lists[i])
pq.push(lists[i]);
while(pq.size())
{
ListNode* temp = pq.top();
pq.pop();
if(!ret)
ret = temp;
else
current ->next = temp;
current = temp;
if(temp ->next)
pq.push(temp ->next);
}
return ret;
}
};