Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
The title means merging K ordered lists into an ordered list.
Ideas:
Using merge sorting, the plot is as follows:
Only in the K-linked list merge, the figure of 10 4 6 and other elements into the list, need Mergetwolist (A, b), the same as the K-linked list as an element of the K elements, 22 merges
The code is as follows:
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x): Val (x), Next (NULL) {} *}; */class Solution {Public:listnode *mergeklists (vector<listnode *> &lists) {if (lists. Size () ==0) return NULL; Return merge (Lists,0,lists.size ()-1); } ListNode *merge (vector<listnode *> &lists,int s,int t)//merge sort {ListNode *p,*q; if (s==t)//returns return Lists[s] If the pointer points to the same lists; else//merge core code {int m= (s+t)/2; Find the middle point p=merge (lists,s,m); Merge the first half part q=merge (LISTS,M+1,T); Merge the latter half of the return mergetwolist (P,Q); Merge the front and back two parts}} listnode *mergetwolist (ListNode *l1,listnode *l2)//merge two linked lists, this part of the code is the source code in the previous question, directly to use the { if (l1==null) return L2; if (l2==null) return L1; ListNode *p,*q; P=L1; Q=L2; ListNode *result=new listnode (0); ListNode *temp =result; while (p&&q) {if (p->val<q->val) {temp->next=p; Temp=p; p=p->next; } else {temp->next=q; temp=q; q=q->next; }} if (p) {temp->next=p; } if (q) {temp->next=q; } return result->next; }};
Time complexity Analysis: The following table is a common recursive relationship
algorithm |
Recursive Relationship |
operation Time |
Notes |
Binary search |
|
|
Scenario Two (k = 0) |
Binary Tree Traversal |
|
|
Situation One |
Merge sort |
|
|
Scenario Two (k = 0)
|
The recursive relationship of the K-linked list is T (k) = 2T (K/2) + O (NK) Here n indicates the length of each linked list K is the number of linked lists
Here is a quick memory method:
T (n) = at (n/b) +c (n^d) Here the n^d is the cost of merging in the K-linked list above n^d for O (NK)
Then you can get the complexity of the problem:
- T (n) = O (n^d log (n)), if a = B^d
- T (n) = O (n^d), if a < b^d
- T (n) = O (N^LOGB (a))), if a > b^d
BecauseT (k) = 2T (K/2) + O (NK) Here a=2,b=2,d=1 (indicates the one-time square of K)
So the complexity of time is NKLOGK
Complexity of space:
Because a merge was not performed, a node was created as a
K/2 + K/4 + k/8 + .....
to K
Merge k Sorted Lists Leetcode