[LeetCode] 23. Merge k Sorted Lists

合并K个排序链表
本文介绍了一种使用最小堆来合并K个已排序链表的方法,并详细分析了该算法的时间复杂度为O(nklogk),空间复杂度为O(kn)。通过创建大小为K的最小堆并循环遍历输入链表的头部节点将其放入堆中,随后从堆中取出最小元素添加到结果链表中,如果该节点有下一个节点,则将它再次插入堆中更新堆。

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Heap

Time Complexity:
Update the heap costs O(nklogk)

Space Complexity:
O(kn)
The result listnode costs O(kn) and the heap is always O(k)

思路

Step1: Create a min heap with size k, loop through the input array of listnode and put all headnode into the heap
Step2: Create a new listnode two store the sorted list
Step3: Do the following steps k*n times (total number of the listnode)
(1) Pop out the min of the heap, add it to the result listnode
(2) If this listnode has next, insert it into the heap and update the heap

*这题中的input中,k个listnode还有其中个别的等于Null的情况,所以要判断一下再加入minheap

代码

public ListNode mergeKLists(ListNode[] lists) {
    if(lists == null || lists.length == 0) return null;
    ListNode dummy = new ListNode(0);
    ListNode head = dummy;
    PriorityQueue<ListNode> minHeap = new PriorityQueue<>(new Comparator<ListNode>(){
        public int compare(ListNode l1, ListNode l2){
            return l1.val - l2.val;
        }
    });
    
    for(int i = 0; i < lists.length; i++){
        if(lists[i] != null) minHeap.offer(lists[i]);
    }
    
    while(!minHeap.isEmpty()){
        ListNode min = minHeap.poll();
        head.next = min;
        head = head.next;
        if(min.next != null){
            minHeap.offer(min.next);
            min = min.next;
        }
    }
    return dummy.next;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值