LeetCode 23 合并K个升序链表(困难)

这篇博客讨论了如何高效地合并多个已排序的链表。提供了三种不同的方法:使用优先级队列、分治合并和传统的双指针法。每种方法的时间复杂度和空间复杂度都有所不同,但都确保了合并后的链表依然有序。通过这些方法,我们可以从给定的链表数组创建一个单一的升序链表。

给你一个链表数组,每个链表都已经按升序排列。

请你将所有链表合并到一个升序链表中,返回合并后的链表。

示例 1

输入:lists = [[1,4,5],[1,3,4],[2,6]]
输出:[1,1,2,3,4,4,5,6]
解释:链表数组如下:
[
	  1->4->5,
	  1->3->4,
	  2->6
]
将它们合并到一个有序链表中得到。
1->1->2->3->4->4->5->6

示例 2

输入:lists = []
输出:[]

示例 3

输入:lists = [[]]
输出:[]

思路与代码

1 k指针

参考 合并两个有序链表
时间复杂度 O(nk) k个链表 代表有k个指针 每次需要比较k个节点哪个最小 n代表节点数量、
时间复杂度 O(1)

2 优先级队列
将K个指针的节点放入优先级队列,这样时间复杂度由k降为log(k)

时间复杂度O(nlog(k))
空间复杂度O(k)

class Solution {
    public ListNode mergeKLists(ListNode[] lists) {      
        if (lists == null || lists.length == 0) return null;
        PriorityQueue<ListNode> queue = new PriorityQueue(new Comparator<ListNode>(){
            public int compare(ListNode a, ListNode b){
                return a.val - b.val;
            }
        });

        for(ListNode node : lists){
            if (node != null) queue.offer(node);
        }

        ListNode sentinel = new ListNode(-1);
        ListNode curNode = sentinel;

        while (!queue.isEmpty()) {
            ListNode node = queue.poll();
            curNode.next = node;
            curNode = node;
            if (node.next != null)
                queue.offer(node.next);
        }
        
        return sentinel.next;
    }
}

3 分治合并
链表两两合并

时间复杂度O(nlog(k)) 这里的log(k)是二分法的复杂度
空间复杂度log(k) 递归会使用到log(k) 空间代价的栈空间

class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) return null;
        return merge(lists, 0, lists.length - 1);
    }

    public ListNode merge(ListNode[] lists, int left, int right){
        if (left == right) return lists[left];
        if (left + 1 == right) return merge2Lists(lists[left], lists[right]);
        
        int mid = left + (right - left) / 2;
        ListNode node1 = merge(lists, left, mid);
        ListNode node2 = merge(lists, mid + 1, right);

        return merge2Lists(node1, node2);
    }

    public ListNode merge2Lists(ListNode l1, ListNode l2){
        ListNode sentine = new ListNode(-1);
        ListNode curNode = sentine;

        while (l1 != null && l2 != null){
            curNode.next = l1.val <= l2.val? l1 : l2;
            curNode = curNode.next;
            if (l1.val <= l2.val) l1 = l1.next;
            else l2 = l2.next;
        }
        curNode.next = l1 != null ? l1 : l2; 
        return sentine.next;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值