Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Tag:使用优先队列,时间复杂度为n*log(k),其中n为所有元素个数,k为已排好序的链表,如果k很小的话,实现复杂度近乎为线性。
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
struct cmp
{
bool operator () (ListNode * const &p1, ListNode * const &p2)
{
return p1->val > p2->val;
}
};
ListNode * mergeKLists(vector<ListNode *> &lists)
{
if(lists.size() == 0)
return NULL;
priority_queue<ListNode *, vector<ListNode *>, cmp> heap;
ListNode * head = NULL;
ListNode * p = NULL;
for(int i = 0; i < lists.size(); i++)
{
if(lists != NULL)
heap.push(lists[i]);
}
while(!heap.empty())
{
if(head == NULL)
{
head = heap.top();
p = head;
}
else
{
p->next = heap.top();
p = p->next;
}
if(heap.top()->next != NULL)
{
heap.push(heap.top()->next);
}
heap.pop();
}
return head;
}