leetcode_效率题解_23. Merge k Sorted Lists(合并k个有序链表)

相关题解:
leetcode_效率题解_[python/C++]_21. Merge Two Sorted Lists(合并2个有序链表)

题目链接
【题目】
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
这里写图片描述
【分析】
想到从第一个链表到最后一个链表逐个合并的思路,当然效率是很低的
但是在leetcode上可以AC(198ms)

解法1:
优先队列优化:

class Solution {
public:
    ListNode *mergeKLists(vector<ListNode *> &lists) {
    std::priority_queue<ListNode*, std::vector<ListNode*>, compare > heap;
    ListNode head(0);
    ListNode *curNode = &head;
    int i, k, n = lists.size();
    for (i = 0; i < n; i++)
        if (lists[i]) heap.push(lists[i]);
    while (!heap.empty()){
        curNode->next = heap.top();
        heap.pop();
        curNode = curNode->next;
        if (curNode->next) heap.push(curNode->next);
    }
    return head.next;
}
struct compare {
        bool operator()(const ListNode* l, const ListNode* r) {
            return l->val > r->val;
        }
    };
};

python
利用python优先队列模块

from Queue import PriorityQueue
class Solution(object):
    def mergeKLists(self, lists):
        dummy = ListNode(None)
        curr = dummy
        q = PriorityQueue()
        for node in lists:
            if node: q.put((node.val,node))
        while q.qsize()>0:
            curr.next = q.get()[1]
            curr=curr.next
            if curr.next: q.put((curr.next.val, curr.next))
        return dummy.next

解法2:递归
效率更高

class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
    int n = lists.size();
    if(n == 0){return nullptr;}
    else if(n == 1){return lists[0];}
    else if(n == 2){return merge2Lists(lists[0],lists[1]);}
    else{
        vector<ListNode*> part1(lists.begin(), lists.begin() + (n)/2);
        vector<ListNode*> part2(lists.begin() + (n)/2 ,lists.end());
        return merge2Lists(mergeKLists(part1),mergeKLists(part2));
    }
}


ListNode* merge2Lists(ListNode* root1, ListNode* root2){
    if(root1 == NULL) return root2;
    if(root2 == NULL) return root1;
    ListNode dummy(0);
    ListNode* p = &dummy;
    while(root1 != NULL && root2 != NULL){
        if(root1->val >= root2->val){
            p->next = root2;
            p = p->next;
            root2 = root2->next;
        }else{
            p->next = root1;
            p = p->next;
            root1 = root1->next;
        }
    }
    if(root1 != NULL){p->next = root1;}
    else if (root2 != NULL){p->next = root2;}

    return dummy.next;
}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值