leetcode 23. Merge k Sorted Lists

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

归并k个链表排序

Solution:
题目类似于上题,但是此题把k不限于为2,这时就不能直接利用归并排序的思想。
因此,此题应该采用堆的思想:
1、将每个非空链表的链头加入最小堆中
2、从堆中取出最小的节点,并在堆中删除,并将next节点放入最小堆中(如果有next)
3、重复2步骤,直至堆空为止。
堆可以采用set或者priority_queue的STL
参照用multiset/priority_Queue来实现最大最小堆

Code:

class Solution {
public:
    typedef pair<ListNode*,int> fun;//the second represents which link the node belongs to 
    struct cmp
    {
        bool operator()(const fun& a,const fun& b)
        {
            return (a.first)->val < (b.first)->val;
        }
    };//redefind the compare function
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        multiset<fun,cmp> se;
        int len=lists.size();
        for(int i=0;i<len;++i)
        {
            if(lists[i])
            {
                se.insert(make_pair(lists[i],i));
                lists[i]=lists[i]->next;
            }
        }//insert the head node of each link which is not empty
        ListNode* pre=NULL;
        bool flag=false;
        ListNode* root=NULL;
        while(!se.empty())
        {
            fun temp=*(se.begin());//get the head of heap
            ListNode* listtemp=new ListNode((temp.first)->val);
            if(pre)
                pre->next=listtemp;
            if(lists[temp.second])
            {
                se.insert(make_pair(lists[temp.second],temp.second));
                lists[temp.second]=lists[temp.second]->next;
            }
            se.erase(se.begin());
            pre=listtemp;
            if(!flag)
            {
                flag=true;
                root=pre;
            }
        }
        return root;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值