leetcode【困难】23、合并K个升序链表

在这里插入图片描述

思路一:归并

假设K个链表,每个长度为n

  • 顺序遍历合并,在第一次合并后,ans 的长度为 n;第二次合并后,ans 的长度为 2×n,第 i 次合并后,ans 的长度为 i×n。总时间复杂度O(k^2 ×n)
    在这里插入图片描述
  • 二分 / 归并,递归
    第一轮合并 k/2 组链表,每一组时间复杂度为 O(2n),第二轮合并 k/4 组链表
    每一组的时间代价是 O(4n)。总时间复杂度为O(kn×logk)。
    在这里插入图片描述
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if(lists.length==0) return null;
        return helper(lists,0,lists.length-1);
    }

    public ListNode helper(ListNode[] lists,int left,int right){
        if(left==right) return lists[left];
        int mid=(left+right)/2;
        ListNode l1=helper(lists,left,mid);
        ListNode l2=helper(lists,mid+1,right);
        return mergeTwo(l1,l2);
    }

    public ListNode mergeTwo(ListNode l1,ListNode l2){
        ListNode pre=new ListNode();
        ListNode p=pre;
        while(l1!=null && l2!=null){
            if(l1.val<l2.val){
                p.next=l1;
                l1=l1.next;
            }else{
                p.next=l2;
                l2=l2.next;
            }
            p=p.next;
        }
        p.next= l1==null?l2:l1;
        return pre.next;
    }
}

思路二:堆排序/优先队列

类似两两合并的操作,先从 k 个链表中找出最小的,安在新链表上,指针后移,将这个最小的节点的next入队,重新排序,接着选最小的

class Solution {
   public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) return null;
        PriorityQueue<ListNode> queue = new PriorityQueue<>(lists.length, new Comparator<ListNode>() {
            @Override
            public int compare(ListNode o1, ListNode o2) {
                if (o1.val < o2.val) return -1;
                else if (o1.val == o2.val) return 0;
                else return 1;
            }
        });
        ListNode dummy = new ListNode(0);
        ListNode p = dummy;
        for (ListNode node : lists) {
            if (node != null) queue.add(node);
        }
        while (!queue.isEmpty()) {
            p.next = queue.poll();
            p = p.next;
            if (p.next != null) queue.add(p.next);
        }
        return dummy.next;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值