translation
合并K个已排序的链表,并且将其排序并返回。分析和描述其复杂性。
Original
andreturnitaslistandits complexity.
Code
We use a divide-and-conquer approach to solve this problem, which has a K-linked list, which is continuously divided (partition) and then merged (merge).
Dividing the part is not difficult, it is divided into two parts, but it should be noted that the start and end of the same situation can occur, this time directly return Lists[start] on it.
midend) / 2-- mid (1)mid1-- end (2)
The above (1) and (2) are constantly replaced with updates, and are constantly written as parameters into the partition function.
The merged part is not difficult, because we have encountered before, Portal: Leetcode, Merge, Sorted Lists.
So the combination is the following:
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x ): Val (x), Next (NULL) {}}; */classSolution { Public: listnode* mergeklists ( vector<ListNode*>&lists) {returnPartition (lists,0, Lists.size ()-1); } listnode* partition ( vector<ListNode*>& Lists,intStartintEnd) {if(start = = end) {returnLists[start]; }if(Start < end) {intMid = (start + end)/2; listnode* L1 = partition (lists, start, mid); listnode* L2 = partition (lists, Mid +1, end);returnMergetwolists (L1, L2); }returnNULL; } listnode* mergetwolists (listnode* L1, listnode* L2) {if(L2 = = NULL)returnL1;if(L1 = = NULL)returnL2;if(L1->val > L2->val) {listnode* temp = L2; Temp->next = mergetwolists (L1, L2->next);returnTemp }Else{listnode* temp = L1; Temp->next = mergetwolists (L1->next, L2);returnTemp } }};
Continue to learn the solution of the Great God:
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x ): Val (x), Next (NULL) {}}; */ classSolution { Public: listnode* mergeklists ( vector<ListNode*>&lists) {intSize = Lists.size ();if(Size = =0)returnNULL;if(Size = =1)returnlists[0];inti =2, J; whileI2< size) { for(j =0; J < size; J + = i) {listnode* p = lists[j];if(j + I/2< size) {p = mergetwolists (p, lists[j + I/2]); LISTS[J] = p; }} I *=2; }returnlists[0]; } listnode* mergetwolists (listnode* L1, listnode* L2) {if(L2 = = NULL)returnL1;if(L1 = = NULL)returnL2;if(L1->val > L2->val) {listnode* temp = L2; Temp->next = mergetwolists (L1, L2->next);returnTemp }Else{listnode* temp = L1; Temp->next = mergetwolists (L1->next, L2);returnTemp } }};
Copyright NOTICE: This article is nomasp Couvant original article, without permission is prohibited reprint! Welcome to my blog: http://blog.csdn.net/nomasp
Leetcode-Merge k Sorted Lists