问题
https://leetcode.com/problems/merge-k-sorted-lists/
解法
使用priority_queue 维护一个小顶堆。
共有k个链表, 所有链表共有n个节点。
复杂度 建立堆 k(logk)
堆中插入一个元素(logk)
共插入n次
总复杂度O(nlogk)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class compare{
public:
bool operator()(ListNode* l1, ListNode* l2)
{
return l1->val > l2->val;
}
};
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode Head(0);
ListNode * ptr = &Head;
priority_queue<ListNode*, vector<ListNode*>, compare> pq;
for (int i=0; i<lists.size(); ++i)
{
if (lists[i])
pq.push(lists[i]);
}
while(pq.size() > 1)
{
ListNode *l = pq.top();
pq.pop();
ptr->next = l;
ptr= ptr->next;
l = l->next;
if (l)
pq.push(l);
}
ptr->next = pq.empty()? 0:pq.top();
return Head.next;
}
};
实现细节
priority_queue 的比较函数有两种定义方式,定义一个compare 类, 另一种是写一个cmp函数,然后将函数传入。
class Foo
{
};
class Compare
{
public:
bool operator() (Foo, Foo)
{
return true;
}
};
int main()
{
std::priority_queue<Foo, std::vector<Foo>, Compare> pq;
return 0;
}
class Foo
{
};
bool Compare(Foo, Foo)
{
return true;
}
int main()
{
std::priority_queue<Foo, std::vector<Foo>, std::function<bool(Foo, Foo)>> pq(Compare);
return 0;
}
priority_queue 默认是建立大顶堆:
Priority queues are a type of container adaptors, specifically designed such that its first element is always the greatest of the elements it contains, according to some strict weak ordering criterion.
如果在compare 中传入 < 则是构建大顶堆
传入> 则是构建小顶堆。