forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution2.java
37 lines (33 loc) · 913 Bytes
/
Solution2.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; }
* }
*/
import java.util.*;
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
ListNode res = new ListNode(0), move = res;
PriorityQueue<ListNode> queue = new PriorityQueue<>(3, new Comparator<ListNode>() {
public int compare(ListNode o1, ListNode o2) {
return o1.val - o2.val;
}
});
for (ListNode node : lists) {
if (node != null) {
queue.offer(node);
}
}
while (!queue.isEmpty()) {
ListNode poll = queue.poll();
move.next = poll;
move = move.next;
if (poll.next != null) {
queue.offer(poll.next);
}
}
return res.next;
}
}