每日一题 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;
    }
};
相关推荐
Tisfy20 分钟前
LeetCode 3838.带权单词映射:求和、取模、拼接(附python一行版)
python·算法·leetcode·字符串·题解·模拟·取模
帅小伙―苏33 分钟前
力扣76最小覆盖子串
算法·leetcode
想吃火锅10051 小时前
【leetcode】20.有效的括号js
linux·javascript·leetcode
Misnearch1 小时前
Leetcode热题100
算法·leetcode·职场和发展
凌波粒2 小时前
LeetCode--1584. 连接所有点的最小费用(最小生成树/Prim算法/Kruskal算法)
算法·leetcode·职场和发展
人道领域21 小时前
【LeetCode刷题日记】47.全排列Ⅱ
java·开发语言·算法·leetcode
Navigator_Z21 小时前
LeetCode //C - 1095. Find in Mountain Array
c语言·算法·leetcode
暖阳华笺1 天前
【数据结构与算法】哈希专题
数据结构·c++·算法·leetcode·哈希算法
AKA__Zas1 天前
芝士算法(滑动窗口片 2.0)
java·算法·leetcode·学习方法
四代水门1 天前
LeetCode刷算法题(C++)
c++·算法·leetcode