leetCode 23
1.题目描述
- 合并K个排序链表
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
--
2.思路
思路:分而治之
有点像归并排序
代码如下
/**
* 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) {
auto dummy = new ListNode(-1);
auto r = dummy;
while(l1 && l2 ) {
if(l1 -> val < l2 -> val) {
r->next = l1;
l1 = l1 -> next;
}
else {
r -> next = l2;
l2 = l2 -> next;
}
r = r -> next;
}
r -> next = nullptr;
if(l1) r->next = l1;
if(l2) r -> next = l2;
return dummy -> next;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.size() == 0) return nullptr;
if(lists.size() == 1) return lists[0];
int mid = lists.size() / 2;
vector<ListNode*> l1(lists.begin(),lists.begin()+mid);
vector<ListNode*> l2(lists.begin()+mid,lists.end());
//for(auto ele : l1) cout<<ele->val<<",";
// cout<<"-----------"<<endl;
//for(auto ele : l2) cout<<ele->val<<",";
ListNode *ml1 = mergeKLists(l1);
ListNode *ml2 = mergeKLists(l2);
return merge(ml1,ml2);
}
};
合并一个两个链表O(n)
分而治之要O(logn)
所以时间复杂度为O(nlogn)