优先队列解法:
public static ListNode mergeKLists2(ListNode[] lists) {
if (lists == null || lists.length == 0) return null;
// 1. 初始化小根堆
PriorityQueue<ListNode> queue = new PriorityQueue((Comparator<ListNode>) (o1, o2) -> (o1.val - o2.val));
for (int i = 0; i < lists.length; i++) {
if (lists[i] != null) queue.add(lists[i]);
}
// 2. 取出堆顶元素,并将堆顶元素的下一节点插入小根堆
ListNode res = new ListNode(0);
ListNode cur = res;
while (!queue.isEmpty()) {
ListNode top = queue.poll();
if (top.next != null) {
queue.add(top.next);
}
cur.next = top;
cur = cur.next;
}
return res.next;
}
reference:https://my.oschina.net/u/4309973/blog/3275955/print
本文介绍了一种使用优先队列(小根堆)高效合并K个已排序链表的方法。通过初始化小根堆并不断取出最小元素,同时将该元素的下一个节点加入堆中,最终实现链表的有序合并。
1026

被折叠的 条评论
为什么被折叠?



