题目:
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
题目链接:Merge k Sorted Lists
C++:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* res = new ListNode(0);
ListNode* head = res;
while(l1!=NULL || l2!=NULL){
if(l1&&l2){
if(l1->val < l2->val){
head->next = l1;
l1 = l1->next;
}
else{
head->next = l2;
l2 = l2->next;
}
head = head->next;
}
while(l1!=NULL && l2==NULL){
head->next = l1;
head = head->next;
l1 = l1->next;
}
while(l1==NULL && l2!=NULL){
head->next = l2;
head = head->next;
l2 = l2->next;
}
}
return res->next;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.empty()){
return NULL;
}
if(lists.size() == 1){
return lists[0];
}
else if(lists.size() == 2){
return mergeTwoLists(lists[0], lists[1]);
}
int mid = lists.size()/2;
vector<ListNode*> l1,l2;
for(int i = 0; i < mid; i++)
l1.push_back(lists[i]);
for(int i = mid; i < lists.size(); i++)
l2.push_back(lists[i]);
ListNode *L1 = mergeKLists(l1);
ListNode *L2 = mergeKLists(l2);
return mergeTwoLists(L1, L2);
}
};
合并排序,分治思想运用