每日一题 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;
    }
};
相关推荐
小欣加油9 小时前
leetcode 62 不同路径
c++·算法·leetcode·职场和发展
夏鹏今天学习了吗9 小时前
【LeetCode热题100(38/100)】翻转二叉树
算法·leetcode·职场和发展
夏鹏今天学习了吗9 小时前
【LeetCode热题100(36/100)】二叉树的中序遍历
算法·leetcode·职场和发展
Mr.Ja9 小时前
【LeetCode热题100】No.11——盛最多水的容器
算法·leetcode·贪心算法·盛水最多的容器
微笑尅乐16 小时前
从暴力到滑动窗口全解析——力扣8. 字符串转换整数 (atoi)
算法·leetcode·职场和发展
zycoder.1 天前
力扣面试经典150题day1第一题(lc88),第二题(lc27)
算法·leetcode·面试
Dream it possible!1 天前
LeetCode 面试经典 150_哈希表_存在重复元素 II(46_219_C++_简单)
leetcode·面试·散列表
学学学无无止境1 天前
组合两个表-力扣
leetcode
天选之女wow1 天前
【代码随想录算法训练营——Day32】动态规划——509.斐波那契数、70.爬楼梯、746.使用最小花费爬楼梯
算法·leetcode·动态规划
红衣小蛇妖1 天前
LeetCode-704-二分查找
java·算法·leetcode·职场和发展