Merge
ksorted linked lists and return it as one sorted list. Analyze and describe its complexity.This problem if there is a 21st merger of two linked list of the basis will be easier, the specific merger linked list when there are two ways
(1) If the K list is connected in turn (L1 and L2 together, the result and L3 together, in turn), the time complexity is n*k*k will time out, the specific calculation method is as follows:Suppose you have a list of k lengths of N (l1,l2,l3...lk), and then calculate the worst-case time complexity,L1+L2---> l12 worst-case operation is 2N timesL12+L3---> l123 worst-case operation is 3N timesAnd so on : Worst case total operation: 2n+3n+4n+...+kn = (2+k) * (k-1) *N/2the time complexity of N*k*k
(2) If the 22 is connected, like a merge sort, the time complexity is N*K*LOGK will not time out;Suppose you have 8 lists (L1,l2,..., l8) of length n, and then calculate the worst-case time complexity:221 Group merge divided into three stages, the first phase is 8 chain list of length n, the number of operations is 2n*4The second phase is a 4-length, 2N linked list, with the number of operations being 4n*2The third stage is a 2-length linked list of 4N, with the number of operations being 8n*1so the total number of operations is n*8*3It is possible to guess half of the conclusion is that the time complexity of K's list with length N is N*k*logk
Leetcode submission results are as follows:
The procedure is as follows:
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 666768 |
/**
* 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* head=
new ListNode(0);
ListNode* p=head;
//head->next为返回的指针
while
(1)
{
if
(l1 && l2){
if
(l1->val<l2->val){
p->next=l1;
p=l1;
l1=l1->next;
}
else
{
p->next=l2;
p=l2;
l2=l2->next;
}
}
else if
(l1 && l2==NULL){
p->next=l1;
break
;
}
else if
(l1==NULL && l2){
p->next=l2;
break
;
}
else
{
break
;
}
}
return head->next;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
if
(lists.size()==0)
return NULL;
vector<ListNode*> old_lists;
//合并前的lists
vector<ListNode*> new_lists;
//合并后的lists
old_lists.clear();new_lists.clear();
for
(
int i=0;i<lists.size();i++)
old_lists.push_back(lists[i]);
while
(1)
{
if
(old_lists.size()==1)
break
;
//合并成一条链表就输出
int cnt=0;
for
(
int i=0;i<old_lists.size()/2;i++)
{
new_lists.push_back(mergeTwoLists(old_lists[cnt],old_lists[cnt+1]));
cnt+=2;
}
if
(cnt<old_lists.size())
//如果链表数是奇数,则合并完前面的两两组合后,还要加入最后一个链表
new_lists.push_back(old_lists[cnt]);
old_lists.clear();
for
(
int i=0;i<new_lists.size();i++)
old_lists.push_back(new_lists[i]);
new_lists.clear();
}
return old_lists[0];
}
};
|
From for notes (Wiz)
Leetcode 23. Merge k Sorted Lists