[LeetCode] Merge K sorted lists

Solution 1:

1. use merge2list(), and merge all lists one by one. Time complexity is O(n*longest list length)

2. For each node, find the smallest node among all head nodes in O(k) time, Time complexity is O(n*k)

3. Use a heap to keep the smallest head node among all head nodes currently (minheap). This the element to add to the merged list is the heap top. Then insert the next pointer to heap top and re-adjust the heap in O(logk). Time complexity is O(n*logk)

Function used: 

make_heap(iterator.begin(), iterator.end(), comp() : //constructor of a new class); iterator can be that of a vector,queue or any capacitor class

pop_heap(iterator.begin(), iterator.end(), comp() ) : just move the top of heap to iterator.end() ... To delete top, call pop_back()

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *mergeKLists(vector<ListNode *> &lists) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        ListNode *head=NULL;
        if(lists.size()==0) return head;
        
        vector<ListNode *> lheap;
        for(int i=0;i<lists.size();i++)
        {
            ListNode* tmp=lists[i];
            if(tmp!=NULL)
                lheap.push_back(tmp); //in case all lists in lists are NULL
        }
        if(lheap.size()==0) return head;
        
        make_heap(lheap.begin(),lheap.end(),comp());
        ListNode *newhead=NULL;
        ListNode *cur=NULL;
        
        while(lheap.size()>0)
        {
            if(head==NULL)
            {
                head=new ListNode(0);
                head=lheap[0];
                cur=new ListNode(0);
                cur=head;
                newhead=new ListNode(0);
                newhead=lheap[0]->next;
            }
            else
            {
                newhead=lheap[0]->next; //update the newhead to be inserted to the heap
                cur->next=lheap[0]; //add new element to merged list head
                cur=cur->next;
            }
            
            //update heap
            pop_heap(lheap.begin(),lheap.end(),comp());//pop heap only moves the top of the heap to the last element in the iterator
            //add new head to header heap
            if(newhead!=NULL)
            {
                lheap[lheap.size()-1]=newhead;
                push_heap(lheap.begin(),lheap.end(),comp());            
            }
            else
                lheap.pop_back();
        }
        
        return head;
    }

class comp {
 public:
    bool operator() (const ListNode* l, const ListNode* r) const {
        return (l->val > r->val); //keep min heap
    }
};

};


你可能感兴趣的:([LeetCode] Merge K sorted lists)