思路:仿照归并排序的思想,n个分成n/2个,再分成n/2/2个直到2个或1个,最后再组合起来。
时间复杂度 O(logN)*N
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* merge_two(ListNode* l1,ListNode* l2){
ListNode* dummy3 = new ListNode(INT_MIN);
ListNode* dummy4 = new ListNode(INT_MIN);
dummy4 ->next = dummy3;
while(l1!=NULL && l2!=NULL){
if(l1->val < l2->val){
dummy3->next = l1;
l1 = l1->next;
}else{
dummy3->next = l2;
l2 = l2->next;
}
dummy3 = dummy3->next;
}
if(l1!=NULL) dummy3->next = l1;
else if(l2!=NULL) dummy3->next = l2;
return dummy4->next->next;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
int n = lists.size();
if(n==0) return NULL;
vector<ListNode*> new_lists;
while(lists.size()!=1){
for(int i=1;i<lists.size();i+=2){
new_lists.push_back(merge_two(lists[i-1],lists[i]));
}
if(lists.size()%2==1) new_lists.push_back(lists.back());
lists = new_lists;
new_lists.clear();
}
return lists[0];
}
};