leetcode[23]Merge k Sorted Lists

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

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
bool comp(ListNode *a, ListNode *b)
{
    return a->val>b->val;
}
class Solution {  
public: 
ListNode *mergeKLists(vector<ListNode *> &lists) 
{
    int n=lists.size();
    if(lists.empty())return NULL;
    vector<ListNode *> v;
    v.reserve(n);
    for (int i=0;i<n;i++)
    {
       if(lists[i]!=NULL)
       v.push_back(lists[i]); 
    }
    if(v.size()==0)return NULL;
    make_heap(v.begin(),v.end(),comp);
    pop_heap(v.begin(),v.end(),comp);
    ListNode *small=v.back();
    v.pop_back();
    ListNode *head=new ListNode(-1);
    ListNode *pL=head;
     pL->next=small;
    pL=pL->next;
    while (!v.empty())
    {
        if (small->next!=NULL)
        {
            v.push_back(small->next);
            push_heap(v.begin(),v.end(),comp);
        }
        pop_heap(v.begin(),v.end(),comp);
        small=v.back();
        v.pop_back();
        pL->next=small;
        pL=pL->next;
    }
    return head->next;
}  
};  
原文地址:https://www.cnblogs.com/Vae1990Silence/p/4283657.html