forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeKSortedList.java
42 lines (35 loc) · 1.01 KB
/
MergeKSortedList.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
38
39
40
41
42
import java.util.Comparator;
import java.util.PriorityQueue;
/**
* https://leetcode.com/articles/merge-k-sorted-list/
*/
public class MergeKSortedList {
// 耗时19ms
// 时间复杂度为O(knlgn)
/**
* 这里要注意lists中可能有node为null
*/
public ListNode mergeKLists(ListNode[] lists) {
ListNode dummy = new ListNode(0), cur = dummy;
PriorityQueue<ListNode> queue = new PriorityQueue<>(new Comparator<ListNode>() {
@Override
public int compare(ListNode node1, ListNode node2) {
return node1.val - node2.val;
}
});
for (ListNode node : lists) {
if (node != null) {
queue.offer(node);
}
}
while (!queue.isEmpty()) {
ListNode node = queue.poll();
cur.next = node;
cur = cur.next;
if (node.next != null) {
queue.offer(node.next);
}
}
return dummy.next;
}
}