LeetCode Java First 400 题解-023

本文介绍了一种高效算法,用于合并多个已排序的链表为一个有序链表。通过使用优先队列(PriorityQueue)的数据结构,可以实现对链表首元素值的快速排序,从而简化合并过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Merge k Sorted Lists    Hard

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

public ListNode mergeKLists(ListNode[] lists) {

    if (lists == null || lists.length == 0)

        return null;

    Queue<ListNode> nodeList = new PriorityQueue<ListNode>(lists.length,

            (m, n) -> (m.val - n.val));

    for (ListNode l : lists) {

        if (l != null) {

            nodeList.add(l);

        }

    }

    ListNode node = new ListNode(0);

    ListNode last = node;

    while (!nodeList.isEmpty()) {

        last.next = nodeList.poll();

        last = last.next;

        if (last.next != null)

            nodeList.add(last.next);

    }

    return node.next;

}
思路:利用PriorityQueue<T>排序能力,根据ListNode首元素值排序。首先把所有的链表全部加入Queue,这时poll就可以得到最小的元素(因原链表已经排序),将最小元素存入目标链表,并把当前链表去除首元素后入队,重复这个过程直到所有结点处理完毕。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值