ID: Code Hoof disease
Yards hoof disease, graduated from Harbin Institute of Technology.
Xiaomi advertising the third generation of advertising engine designers, developers;
Responsible for Xiaomi application store, calendar, open screen advertising business Line research and development;
Leading Xiaomi advertising engine multiple module reconfiguration;
focus on recommendations, search, advertising and related knowledge;
Topics
Merges the K sorted list and returns the sorted list after the merge. Please analyze and describe the complexity of the algorithm.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
Analysis
In front of the two ordered list of the merger, as long as two points, divide and conquer, 22 merge can be. In terms of time complexity, the time complexity of merging the length of the two linked lists is O (min (m, n)), where m,n is the length of the linked list, respectively. The length of the two merges is the time complexity of O (LOGK). So the overall time complexity is O (KLOGN)
Code
/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution { PublicListNode mergetwolists (listnode L1, ListNode L2) {if(L1 = =NULL) { returnL2; } if(L2 = =NULL) { returnL1; } ListNode merged=NULL; ListNode Head=NULL; while(L1! =NULL&& L2! =NULL) { if(Head = =NULL) { if(L1.val <l2.val) {merged=L1; L1=L1.next; } Else{merged=L2; L2=L2.next; } head=merged; Continue; } if(L1.val <l2.val) {Merged.next=L1; L1=L1.next; } Else{Merged.next=L2; L2=L2.next; } merged=Merged.next; } while(L1! =NULL) {Merged.next=L1; L1=L1.next; Merged=Merged.next; } while(L2! =NULL) {Merged.next=L2; L2=L2.next; Merged=Merged.next; } returnHead; } PublicListNode mergehelper (listnode[] lists,intLowintHigh ) { if(Low <High ) { intMid = (low + high)/2; ListNode leftlist=Mergehelper (lists, low, mid); ListNode rightlist= Mergehelper (lists, Mid + 1, high); returnmergetwolists (leftlist, rightlist); } returnLists[low]; } PublicListNode mergeklists (listnode[] lists) {if(Lists = =NULL|| Lists.length = = 0) { return NULL; } returnMergehelper (lists, 0, lists.length-1); }}
Expand
Merge two ordered linked lists, previously using a non-recursive solution. Feel the code is a bit long, can use recursive solution, shorten the code amount. When merging, select the smallest element, then move the list head pointer and merge recursively.
Public classSolution { PublicListNode mergetwolists (listnode L1, ListNode L2) {if(L1 = =NULL&& L2 = =NULL) { return NULL; } if(L1 = =NULL) { returnL2; } if(L2 = =NULL) { returnL1; } ListNode merged; if(L1.val >l2.val) {merged=L2; L2=L2.next; Merged.next=mergetwolists (L1, L2); } Else{merged=L1; L1=L1.next; Merged.next=mergetwolists (L1, L2); } returnmerged; }}
Related Topics
21. Merging two ordered linked lists
23. Merging K sort lists