每日一题 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;
    }
};
相关推荐
XiaoyaoCarter1 小时前
每日一道leetcode
c++·算法·leetcode·职场和发展·二分查找·深度优先·前缀树
软行4 小时前
LeetCode 每日一题 3341. 到达最后一个房间的最少时间 I + II
数据结构·c++·算法·leetcode·职场和发展
How_doyou_do4 小时前
备战菊厂笔试4
python·算法·leetcode
緈福的街口7 小时前
【leetcode】94. 二叉树的中序遍历
算法·leetcode
小羊在奋斗9 小时前
【LeetCode 热题 100】搜索插入位置 / 搜索旋转排序数组 / 寻找旋转排序数组中的最小值
算法·leetcode·职场和发展
林下清风~12 小时前
力扣hot100——347.前K个高频元素(cpp手撕堆)
算法·leetcode·职场和发展
小雅痞12 小时前
[Java][Leetcode middle] 238. 除自身以外数组的乘积
java·leetcode
进击的小白菜13 小时前
Java回溯算法解决非递减子序列问题(LeetCode 491)的深度解析
java·算法·leetcode
Swift社区14 小时前
涂色不踩雷:如何优雅解决 LeetCode 栅栏涂色问题
算法·leetcode·职场和发展
冠位观测者14 小时前
【Leetcode 每日一题】2900. 最长相邻不相等子序列 I
数据结构·算法·leetcode