23. Merge k Sorted Lists
Last updated
Last updated
Merge多個sorted list並回傳完整的sorted list.
分析並解釋他的Complexity
Merge sort, 省略掉split的部分, 將每個sorted list當成最小的單位
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* merge(ListNode* l1, ListNode *l2){
if(!l1){
return l2;
}
if(!l2){
return l1;
}
ListNode *res = nullptr;
ListNode **ptr;
if(l1->val < l2->val){
res = l1;
l1 = l1->next;
}else{
res = l2;
l2 = l2->next;
}
ptr = &res;
//Merge 2 list
while(l1 && l2){
if(l1->val < l2->val){
(*ptr)->next = l1;
l1 = l1->next;
}else{
(*ptr)->next = l2;
l2 = l2->next;
}
ptr = &((*ptr)->next);
}
if(l1){
(*ptr)->next = l1;
}else if(l2){
(*ptr)->next = l2;
}
return res;
}
ListNode *mergeK(vector<ListNode*>::iterator b, vector<ListNode*>::iterator e){
if(b == e){
return nullptr;
}
if(next(b) == e){
return *b;
}
int mid = distance(b,e)/2;
ListNode *left= mergeK(b,b + mid);
ListNode *right = mergeK(b + mid,e);
return merge(left,right);
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
return mergeK(lists.begin(),lists.end());
}
};