-
Notifications
You must be signed in to change notification settings - Fork 0
/
23. 合并K个排序链表(堆排序).java
37 lines (37 loc) · 1.15 KB
/
23. 合并K个排序链表(堆排序).java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
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 l1, ListNode l2) {
return l1.val - l2.val;
}
});
// 遍历链表数组,然后将每个链表的每个节点都放入堆中
for (int i = 0; i < lists.length; i++) {
while (lists[i] != null) {
queue.add(lists[i]);
lists[i] = lists[i].next;
}
}
ListNode dummy = new ListNode(-1);
ListNode head = dummy;
// 从堆中不断取出元素,并将取出的元素串联起来
while (!queue.isEmpty()) {
dummy.next = queue.poll();
dummy = dummy.next;
}
dummy.next = null;
return head.next;
}
}