[Leetcode] Merge k Sorted Lists

Source: Internet
Author: User

https://oj.leetcode.com/problems/merge-k-sorted-lists/

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

Solution:

1. O (NK2) runtime, O (1) Space–brute Force:

The brute force approach is-to-merge a list one by one. For example, if the lists = [L1, L2, L3, L4], we first merges L1 and L2, then merge the result W ITH L3, and finally L4.

To analyze it time complexity, we are going to assume there be a total of K lists, and each list is of size n . There is a total of k–1 merge operations. The first merge operation would be a lists of size n , therefore in the worst case there could is n + N Comparisons. The second merge operation would be a lists of size 2n and n . Notice that all merge increase the size of the merged lists by N . Therefore, the total number of comparisons required is 2n + 3n + 4n + ... + kn = n (k (k+1)/2-1) = O (NK2).

2. O (nklogk) runtime, O (k) Space–heap:
We could use a min heap of size K. The heap is first initialized with the smallest element from each list. Then as we extract the "nodes out" from the heap, we must remember to inserts its next node into the heap. As each insert operation into the heap costs log (k) and there is a total of NK elements, the total runtime compl Exity is O (NKLOGK).

Ignoring the extra space is used to store the output list, we have the use extra space of O (k) due to the heap.

/** * AUTHOR:ACJX * Email: [Email protected]*//** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classcmp{ Public:        BOOL operator() (ConstListNode *LHS,ConstListNode *RHS) {            returnLhs->val > Rhs->Val; }};classSolution { Public: ListNode*mergeklists (Vector<listnode *> &lists) {        if(Lists.empty ())returnNULL; Priority_queue<listnode, Vector<listnode *>, cmp>queue;  for(ListNode *&nodeptr:lists) {            if(Nodeptr! =NULL)            {Queue.push (nodeptr); }} ListNode*dummyhead =NewListNode (0); ListNode*p =Dummyhead;  while(!Queue.empty ()) {ListNode*nodeptr =Queue.top ();            Queue.pop (); P->next =nodeptr; P= p->Next; if(Nodeptr->next! =NULL) {Queue.push (nodeptr-next); }        }                returnDummyhead->Next; }};

3. O (NK log k) runtime, O (1) Space–divide and conquer using a. Merge:
If you still remember how the merge sort works, we can use a divide and conquer mechanism to solve this problem. Here, we apply the merge to both lists algorithm from Article[merge to Sorted lists].

Basically, the algorithm merges the lists at a time, so the number of lists reduces from:

k–> k/2–> k/4–> ...–> 2–> 1

Similarly, the size of the lists increases from (Note so the lists could subdivide itself at most log (k) times) :

n–> 2n–> 4n–> ...–> 2logkn

Therefore, the runtime complexity is:

K * n + k/2 * 2n + K/4 * 4n + ... + 2logkn * 1
= nk + nk + NK + ... + NK
= Nklogk

Since we implementing this divide and conquer algorithm iteratively, the space complexity is constant at O (1) , yay!

/** * AUTHOR:ACJX * Email: [Email protected]*//** 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) {        if(Lists.empty ())returnNULL; intEnd = Lists.size ()-1;  while(End >0)        {            intBegin =0;  while(Begin <end) {Lists[begin]=merge2lists (Lists[begin], lists[end]); ++begin; --end; }        }        returnLists.at (0); }    Private: ListNode*merge2lists (ListNode *l1, ListNode *L2) {ListNode*dummyhead =NewListNode (0); ListNode*p =Dummyhead;  while(L1! = NULL && L2! =NULL) {            if(L1->val < l2->val) {P->next =L1; L1= l1->Next; }            Else{p->next =L2; L2= l2->Next; } P= p->Next; }                if(L1! = NULL) P->next =L1; if(L2! = NULL) P->next =L2; returnDummyhead->Next; }};

[Leetcode] 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.