zoukankan      html  css  js  c++  java
  • 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;
    }  
    };  
  • 相关阅读:
    DBCP数据库连接池
    Java Ant build.xml详解
    AWK 用法
    java打jar包
    linux 下java jar包的方法
    linux下java命令行引用jar包
    java webservice
    设计模式的几大原则
    ContextLoaderListener
    WebApplicationContextUtils源码
  • 原文地址:https://www.cnblogs.com/Vae1990Silence/p/4283657.html
Copyright © 2011-2022 走看看