23.Merge k Sorted Lists (Array; Sort)

Source: Internet
Author: User

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

Idea I: Select sort

Each time you compare the Val of the head pointer of each list, take the smallest one. Time complexity O (n2)

Result:time Limit exceeded

Idea II: Minimum heap.

Time Complexity: Heap sequencing is also a sort of selection. Just select the sort directly, in order to select the maximum record from R[1...N], you need to compare n-1 times, then select the maximum record from r[1...n-2] to compare n-2 times. In fact, many of these n-2 comparisons have already been made in the previous n-1 comparisons, and the tree-shaped selection sort happens to preserve some of the previous comparisons by using the tree shape feature, thus reducing the number of comparisons. Time Complexity of O (NLOGN)

Heap sorting thought reference: http://jingyan.baidu.com/article/5225f26b057d5de6fa0908f3.html

classSolution { Public: ListNode*mergeklists (Vector<listnode *> &lists) {        //using heap sorting,//1. Select the head of each linked list to insert into the small top heap,//2. The top of the heap is connected to the linked list,//3. The selected pointer moves back and then joins the small top heap, returning to 2//4. When all of the last linked lists are empty, return the header pointer of the merged list        if(Lists.empty ())returnnullptr; Vector<listnode* >Heap; Heap.push_back (0);//padding//1. Select the head of each linked list to insert into the small top heap,         for(inti =0; I! = Lists.size (); i + +){           if(Lists[i]) heap.push_back (lists[i]);        } makeheap (heap); //2. The top of the heap is connected to the linked list,ListNode Head (-1);//table header for merging listslistnode* p = &Head;  while(Heap.size () >1) {Auto Minnode= heap[1]; P->next = Minnode;//Access linked listp = p->Next; //3. The selected pointer moves back and then joins the small top heap, returning to 2Auto Next = minnode->Next; if(next) {heap[1] =Next; }Else{swap (heap[1], heap[heap.size ()-1]);            Heap.pop_back (); } minheap (Heap,1);//after adding a new element to the top of the heap, adjust it from top to bottom        }        //4. When all of the last linked lists are empty, return the header pointer of the merged list        returnHead.next; }    //build a small top pile//from bottom up    voidMakeheap (Vector<listnode*> &heap) {        //Create a small top heap starting from the parent of the last element         for(inti = (heap.size ()-1)/2; i >0; I--) {minheap (heap, i); }    }    //small Top heap, with the first element as the root to build a small top heap//position starting from 1, when taking elements remember-1//from top to bottom    voidMinheap (vector<listnode*> &heap,inti) {        intL = i*2; intR = L +1; intleast (i); //figure out the position of the smallest element        if((l< heap.size ()) && heap[l]->valval) {            //If the border is not exceeded and the left child is smaller than the father, changeleast =l; }        if(Rval) {            //if the boundary is not exceeded and the right child is the smallest, changeleast =R; }        if(Least! =i)            {Swap (Heap[i], heap[least]); Minheap (heap, least);//after the change, continue to adjust downwards        }    }};

Idea III: Merge sort

Initial state: 6,202,100,301,38,8,1 after first merge: {6,202},{100,301},{8,38},{1}, number of comparisons: 3; After the second merge: {6,100,202,301},{1,8,38}, Comparison number: 4 ; After the third merge: {1,6,8,38,100,202,301}, compare number of times: 4;reference:http://baike.baidu.com/link?url=ayx3mqx_ Crmcjoxkl7ekhxuklh9pjkjsd1xdmap6eqwvffc-btnqbutselrafxbxqhcfoilkc5vsl14lgjejik Merge sort time complexity O (NLOGN)
/** 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; MergeSort (lists,0, Lists.size ()-1); returnlists[0]; }    voidMergeSort (vector<listnode*>& lists,intStartintend) {        if(Start==end)return; intMid = (start + end) >>1;        MergeSort (lists, start, mid); MergeSort (lists, mid+1, end); Merge (Lists,start, Mid+1); }        voidMerge (vector<listnode*>& lists,intLst1,intlst2) {ListNode* Root =NULL; ListNode* current =NULL;  while(Lists[lst1] &&Lists[lst2]) {            if(Lists[lst1]->val <= lists[lst2]->val) {                if(!root) {Root=Lists[lst1]; Current=Root; }                Else{ Current->next =Lists[lst1]; Current= current->Next; } Lists[lst1]= lists[lst1]->Next; }            Else{                if(!root) {Root=Lists[lst2]; Current=Root; }                Else{ Current->next =Lists[lst2]; Current= current->Next; } Lists[lst2]= lists[lst2]->Next; }        }                 while(Lists[lst1]) {if(!root) {Root=Lists[lst1]; Current=Root; }            Else{ Current->next =Lists[lst1]; Current= current->Next; } Lists[lst1]= lists[lst1]->Next; }         while(Lists[lst2]) {if(!root) {Root=Lists[lst2]; Current=Root; }            Else{ Current->next =Lists[lst2]; Current= current->Next; } Lists[lst2]= lists[lst2]->Next; } Lists[lst1]=Root; }};

23.Merge k Sorted Lists (Array; Sort)

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.