[归并] 合并K个排序链表

合并K个排序链表

思路:

暴力合并为一个链表后sort(误!)

插堆还原(误!)

每次选一个最小的插入(堆优化选择过程) 复杂度log(k)*sum(len)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:

    struct rnode
    {
        ListNode *it;
        bool operator < (const rnode b) const
        {
            return -it->val < -b.it->val; 
        }
    };

    ListNode* mergeKLists(vector<ListNode*> &lists)  {
        priority_queue <rnode> Q;

        ListNode *head = new ListNode(0);
        ListNode *it = head;

        for(auto x : lists)
        {
            if(x != NULL)
            {
                Q.push(rnode{x});
            }
        }

        while(!Q.empty())
        {
            auto now = Q.top();
            Q.pop();
            it->next = now.it;
            it = it->next;
            if(now.it->next != NULL)
            {
                Q.push(rnode{now.it->next});
            }
        }

        return head->next;
    } 
};

两两合并直到只剩一个(递归)复杂度log(k)*sum(len)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:

    ListNode *merge(ListNode *a, ListNode *b)
    {
        ListNode *ret = new ListNode(0);
        ListNode *now = ret;
        while(a != NULL && b != NULL)
        {
            if(a->val <= b->val)
            {
                now->next = a;
                a = a->next;
                now = now->next;
            }
            else
            {
                now->next = b;
                b = b->next;
                now = now->next;
            }
        }

        while(a != NULL)
        {
            now->next = a;
            a = a->next;
            now = now->next;
        }
        while(b != NULL)
        {
            now->next = b;
            b = b->next;
            now = now->next;
        }
        return ret->next;
    }

    ListNode* mergeKLists(vector<ListNode*> &lists) {
        while(lists.size() >= 2)
        {
            vector <ListNode*> ret;
            for(int i = 0; i < lists.size(); i += 2)
            {
                if(i != lists.size() - 1)
                {
                    ret.push_back(merge(lists[i], lists[i + 1]));
                }
                else
                {
                    ret.push_back(lists[i]);
                }
            }
            lists = ret;
        }
        return lists.size() ? lists[0] : NULL;
    }
};

Done!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值