码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode[23]Merge k Sorted Lists

时间:2015-02-10 15:08:02      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

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;
}  
};  

 

leetcode[23]Merge k Sorted Lists

标签:

原文地址:http://www.cnblogs.com/Vae98Scilence/p/4283657.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!