LeetCode23-合并K个升序链表

LeetCode23-合并K个升序链表

堆/优先队列实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public ListNode mergeKLists(ListNode[] lists) {
if (lists.length == 0 || lists == null) return null;
PriorityQueue<Integer> queue = new PriorityQueue<>(((o1, o2) -> o2-o1));
ListNode res = new ListNode();
ListNode node = null;
for (ListNode list : lists) {
node = list;
while (node != null) {
queue.offer(node.val);
node = node.next;
}
}
ListNode next = null;
int size = queue.size();
for (int i = 0; i < size; i++) {
next = res.next;
Integer val = queue.poll();
node = new ListNode(val, next);
res.next = node;
}
return res.next;
}