Problem: MergeKSorted linked lists and return it as one sorted list. analyze and describe its complexity.
Merge two lists first, and then combine them recursively Based on the Merge Sorting method. Suppose there are a total of K lists, and the maximum length of each list is N, then the running time must meet the recursive T (K) = 2 T (K/2) + O (N * K ). According to the main theorem, the total complexity of the algorithm is O (nklogk ). The space complexity is the size of the recursive stack O (logk ).
/*** 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) // set the two list merge {If (! L1) return L2; If (! L2) return L1; listnode * TMP = new listnode (0); listnode * ans = TMP; while (L1 & l2) {If (L1-> Val <L2-> Val) {ANS-> next = L1; ans = ANS-> next; L1 = L1-> next ;} else {ANS-> next = L2; ans = ANS-> next; L2 = L2-> next ;}} if (L1) {While (L1) {ANS-> next = L1; ans = ANS-> next; L1 = L1-> next ;}} if (L2) {While (L2) {ANS-> next = L2; ans = ANS-> next; L2 = L2-> next;} ans = TMP; Delete ans; return TMP-> next ;} listnode * remerge (vector <listnode *> & lists, int L, int R) {If (L <r) // similar to Merge Sorting, split a large block into two blocks: L and R, and then merge the two blocks (L and R can be further divided) {int M = (L + r)/2; return mergetwolists (remerge (lists, l, m), remerge (lists, m + 1, R);} else return lists [l];} listnode * mergeklists (vector <listnode *> & lists) {listnode * ans = NULL; // use null instead of using new listnode (0) if (lists. size () = 0) return ans; return remerge (lists, 0, lists. size ()-1 );}};
Leetcode 22nd -- merge K sorted lists