每日一题 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;
    }
};
相关推荐
墨染点香8 小时前
LeetCode 刷题【146. LRU 缓存】
leetcode·缓存·哈希算法
qk学算法8 小时前
力扣滑动窗口题目-76最小覆盖子串&&1234替换子串得到平衡字符串
数据结构·算法·leetcode
小欣加油8 小时前
leetcode 860 柠檬水找零
c++·算法·leetcode·职场和发展·贪心算法
还是码字踏实8 小时前
基础数据结构之数组的矩阵遍历:螺旋矩阵(LeetCode 54 中等题)
数据结构·leetcode·矩阵·螺旋矩阵
im_AMBER11 小时前
算法笔记 10
笔记·学习·算法·leetcode
夏鹏今天学习了吗19 小时前
【LeetCode热题100(59/100)】分割回文串
算法·leetcode·深度优先
还是码字踏实19 小时前
基础数据结构之数组的双指针技巧之对撞指针(两端向中间):三数之和(LeetCode 15 中等题)
数据结构·算法·leetcode·双指针·对撞指针
轮到我狗叫了1 天前
力扣.84柱状图中最大矩形 力扣.134加油站牛客.abb(hard 动态规划+哈希表)牛客.哈夫曼编码
算法·leetcode·职场和发展
熬了夜的程序员1 天前
【LeetCode】99. 恢复二叉搜索树
算法·leetcode·职场和发展
Kent_J_Truman1 天前
LeetCode Hot100 自用
算法·leetcode·职场和发展