23. Merge k Sorted Lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
Example 1:
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
1->4->5,
1->3->4,
2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6
Example 2:
Input: lists = []
Output: []
Example 3:
Input: lists = [[]]
Output: []
题意:
合并k个有序链表
思路:
归并排序,采用分治的思想。将整段list逐渐划分,直至不能继续划分为止。然后合并此时的两段序列。采用自底向上的思想,最后输出根节点。
时间复杂度:O(NlogK),空间复杂度:O(1)(由于合并的是链表,只需考虑一个临时节点dummy(0))
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
//合并k个有序链表
//归并的思想
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.size()==0) return NULL;
if(lists.size()==1) return lists[0];
int l=0,r=lists.size()-1;
ListNode *ans=split(lists,l,r);
return ans;
}
ListNode* split(vector<ListNode*>& lists,int l,int r){
if(l>r) return NULL;
if(l==r){
return lists[l];
}
int mid=(l+r)>>1;
ListNode* s= split(lists,l,mid);
ListNode* t= split(lists,mid+1,r);
ListNode *ans=merge(s,t);
return ans;
}
ListNode *merge(ListNode *s,ListNode *t){
// cout<<s->val << t->val <<"\n";
ListNode dummy(0);
ListNode *p=&dummy;
while(s && t){
if(s->val < t->val){
p->next=s;
s=s->next;
}
else{
p->next=t;
t=t->next;
}
p=p->next;
}
if(s) p->next=s;
if(t) p->next=t;
return dummy.next;
}
};