23. Merge k Sorted Lists
Hard
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
Accepted
478,157
Submissions
1,303,920
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
int num=lists.size();
ListNode* temp;
if(num==0) return NULL;
else{temp=lists[0];}
for(int i=1;i<num;i++){
temp=mergeTwoLists(temp,lists[i]);
}
return temp;
}
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* head=new ListNode(0);//dummy head
ListNode* p=head;
while(l1!=NULL&&l2!=NULL){
if(l1->val<=l2->val){
p->next=l1;
l1=l1->next;
p=p->next;
p->next=NULL;
}else{
p->next=l2;
l2=l2->next;
p=p->next;
p->next=NULL;
}
}
if(l1!=NULL) p->next=l1;
else if(l2!=NULL) p->next=l2;
head=head->next;
return head;
}
};
这道题用优先队列做比较好,下面为参考代码:
struct cmp {
bool operator()(ListNode * x, ListNode * y) {//重载运算符
return x->val > y->val;
}
};
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
priority_queue<ListNode*, vector<ListNode*>, cmp> q;
for(int i = 0; i < lists.size(); i++)
if(lists[i] != NULL)
q.push(lists[i]);
ListNode *dummy = new ListNode(0);
ListNode *cur = dummy, *tmp = NULL;
while(!q.empty()) {//比较头元素
tmp = q.top();
q.pop();
cur->next = tmp;
cur = cur->next;
if(tmp->next != NULL)
q.push(tmp->next);
}
cur = dummy->next;
delete dummy;
return cur;
}
};