Leetcode 22nd -- merge K sorted lists

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.