每日一题 LCR 078. 合并 K 个升序链表

LCR 078. 合并 K 个升序链表

使用二分法就可以解决

cpp 复制代码
class Solution {
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {

        int n = lists.size();

        if(n == 0){
            return nullptr;
        }
        ListNode* ans ;

        ans = binMerge(lists,0,n-1);
        return ans;
    }

    ListNode* binMerge(vector<ListNode*> &lists,int l,int r ){
        //cout<<l<<" "<<r<<endl;
        if(l > r){
            return nullptr;
        }
        if(l == r){
            return lists[l] ;
        }
        int mid = (l+r)/2;
        ListNode* ll = binMerge(lists,l,mid);
        ListNode* rr = binMerge(lists,mid+1,r);

        return mergeListTwo(ll,rr);
    }

    ListNode* mergeListTwo(ListNode* l, ListNode* r){
        
        ListNode* dummy = new ListNode(0);
        ListNode* h = dummy;
        while(l && r){
            if(l->val > r->val){
                h->next = r;
                r = r->next;
            }else{
                h->next = l;
                l = l->next;
            }
            h = h->next;
        }
        if(l){
            h->next = l;
        }
        if(r){
            h->next = r;
        }
        return dummy->next;
    }
};
相关推荐
艾莉丝努力练剑4 小时前
【LeetCode&数据结构】单链表的应用——反转链表问题、链表的中间节点问题详解
c语言·开发语言·数据结构·学习·算法·leetcode·链表
珊瑚里的鱼9 小时前
LeetCode 692题解 | 前K个高频单词
开发语言·c++·算法·leetcode·职场和发展·学习方法
凌肖战13 小时前
力扣网编程135题:分发糖果(贪心算法)
算法·leetcode
Norvyn_715 小时前
LeetCode|Day11|557. 反转字符串中的单词 III|Python刷题笔记
笔记·python·leetcode
chao_78915 小时前
动态规划题解_零钱兑换【LeetCode】
python·算法·leetcode·动态规划
吃着火锅x唱着歌15 小时前
LeetCode 424.替换后的最长重复字符
linux·算法·leetcode
Maybyy15 小时前
力扣454.四数相加Ⅱ
java·算法·leetcode
逐闲19 小时前
LeetCode热题100【第一天】
算法·leetcode
爱吃涮毛肚的肥肥(暂时吃不了版)19 小时前
剑指offer——模拟:顺时针打印矩阵
算法·leetcode·矩阵
chao_78919 小时前
动态规划题解——乘积最大子数组【LeetCode】
python·算法·leetcode·动态规划