Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
思路:用一个 prority_queue
来存放所有的链表,每次取顶端元素即可。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
struct compare{
bool operator()(const ListNode* a,const ListNode* b){
return a->val>b->val;
}
};
ListNode *mergeKLists(vector<ListNode*> &lists){
priority_queue<ListNode*, vector<ListNode*>, compare> q;
int sz=lists.size();
if(!sz)return NULL;
for(int i=0;i<sz;i++)
if(lists[i])q.push(lists[i]);
if(q.empty())return NULL;
ListNode* res=q.top();q.pop();
if(res->next)q.push(res->next);
ListNode* p=res;
while(!q.empty()){
p->next=q.top();q.pop();
p=p->next;
if(p->next)q.push(p->next);
}
return res;
}
};