Merge k Sorted Lists Leetcode

Source: Internet
Author: User

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Hide TagsDivide and Conquer Linked List HeapHide Similar Problems(E) Merge Sorted Lists (M) Ugly number IIThe title means merging multiple ordered lists! Use divide-and-conquer recursion! The first way of thinking analysis: Divide and conquer, continue to divide, until it becomes a sub-problem of two ordered list merging! The merged dynamic diagram is shown on the right: the subject is built on the basis of merging two sequential linked list algorithms, merging two ordered sub-lists continuously until the entire sub-linked list is merged into one. This topic is very common in distributed systems, and the sorted list from different clients is to be combined on the central server. Let's analyze the time complexity of the above algorithm. Assuming that there is a total of K lists, the maximum length of each list is n, then the run time satisfies the recursive t (k) = 2T (K/2) +o (n*k). According to the main theorem, the total complexity of the algorithm can be calculated as O (nklogk). If you do not know the main theorem of friends, you can see the main theorem-Wikipedia. Space complexity is the size of the recursive stack O (logk). The code is implemented as follows:
1#include <iostream>2#include <vector>3 using namespacestd;4 5 structListNode {6     intVal;7ListNode *Next;8ListNode (intx): Val (x), Next (NULL) {}9 };Ten  One classSolution { A  Public: -listnode* mergeklists (vector<listnode*>&lists) -     { the         if(lists.size () = =0) -             returnNULL; -         if(lists.size () = =1) -             returnlists[0]; +         //vector<listnode*> Res; -          while(Lists.size ()! =1) +         { Alistnode*temp= mergetwolists (lists[0], lists[1]); at Lists.push_back (temp); - lists.erase (Lists.begin ()); - lists.erase (Lists.begin ()); -         } -         returnlists[0]; -  in     } -listnode* mergetwolists (listnode* L1, listnode*L2) to     { +         if(!L1) -             returnL2; the         if(!L2) *             returnL1; $ListNode N1 (-1);Panax NotoginsengN1.next =L1; -ListNode *ptr1 = L1, *pre1, *ptr2 = L2, *B2; thePre1 = &N1; +          while(PTR2) A         { theB2 = ptr2->Next; +             if(Ptr1->val < ptr2->val) -             { $PTR1 = ptr1->Next; $Pre1 = pre1->next;/// -                 if(ptr1 = = NULL)//it has to be terminated here! Otherwise the run will be faulted -                      Break; the             } -             ElseWuyi             { thePre1->next =ptr2; -Ptr2->next =ptr1; WuPTR2 =B2; -Pre1 = pre1->next;/// About             } $         } -         if(PTR2! =NULL) -Pre1->next =ptr2; -         returnN1.next; A     } + }; the  - intMain () $ { the solution test; the  theVector<listnode*>Val; theListNode *n1 =NULL; -ListNode N2 (-1), N3 (5), N4 ( One); inN2.next = &N3; theN3.next = &N4; theListNode *n5 =NULL; AboutListNode N6 (6), N7 (Ten); theN6.next = &N7; the Val.push_back (N1); theVal.push_back (&n2); + Val.push_back (N5); -Val.push_back (&N6); the     //cout << "The size of Val:" << val.size () << "" << val.capacity () << Endl;Bayilistnode* result =Test.mergeklists (val); the      while(Result) the     { -cout << Result->val <<" "; -result = Result->Next; the     } the     return 0; the}
View Code

The second way of thinking analysis (used in the heap of this data structure): The idea is more difficult to think of, but in fact the principle is relatively simple. Maintain a heap of size k, each fetch the smallest element of the heap top into the result, then read the next element of the element into the heap and re-maintain it. Because each list is ordered, each time it goes to the smallest of the current k elements, when all the linked lists are finished, all the elements are placed from small to large in the result list. Each element of this algorithm is read once, that is, k*n times, and then each time the element is read to insert the new element into the heap to logk complexity, so the total time complexity is O (NKLOGK). The spatial complexity is the size of the heap, which is O (k).

Merge k Sorted Lists Leetcode

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.