leetcode:合并k个升序链表

复制代码
//分治
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* a,ListNode* b){
        ListNode* dummynode=new ListNode(0);
        ListNode* cur=dummynode;
        while(a!=nullptr && b!=nullptr){
            if(a->val<=b->val){
                cur->next=a;
                a=a->next;
            }
            else{
                cur->next=b;
                b=b->next;
            }
            cur=cur->next;
        }
        if(a==nullptr) cur->next=b;
        if(b==nullptr) cur->next=a;
        return dummynode->next;
    } 

    ListNode* merge(vector<ListNode*> &lists,int l,int r){
        if(l==r) return lists[l];
        if(l>r) return nullptr;
        int mid=l+(r-l)/2;
        return mergeTwoLists(merge(lists,l,mid),merge(lists,mid+1,r));
    }

    ListNode* mergeKLists(vector<ListNode*> lists){
        return merge(lists,0,lists.size()-1);
    }
};
复制代码
复制代码
//优先级队列
class Solution {
public:
    struct comp{//重写仿函数
        bool operator()(ListNode* a,ListNode* b){
            return a->val>b->val;//堆顶元素是排序元素的末尾,小顶堆
        }
    };
    priority_queue<ListNode* , vector<ListNode*> , comp> q;
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        for(auto node:lists){
            if(node) q.push(node);
        }
        ListNode* head=new ListNode(-1);
        ListNode* tail=head;
        while(!q.empty()){
            ListNode* node=q.top();
            q.pop();
            tail->next=node;
            tail=tail->next;
            if(node->next) q.push(node->next);


        }
        return head->next;
    }
};
复制代码

 

 

posted @   Ojalá  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示