-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
45 lines (40 loc) · 1.12 KB
/
Solution.java
File metadata and controls
45 lines (40 loc) · 1.12 KB
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
43
44
45
package leetCode_23;
import java.util.Comparator;
import java.util.PriorityQueue;
/**
* @author dimdark
* @date 2017-10-08
* @time 7:14 PM
*/
public class Solution {
class ListNode {
int val;
ListNode next;
ListNode(int x) {
this.val = x;
}
}
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0) return null;
PriorityQueue<ListNode> q = new PriorityQueue<ListNode>(lists.length, Comparator.comparingInt(node -> node.val));
ListNode falseHead = new ListNode(-1);
ListNode currentNode = falseHead;
// initial
for (int i = 0; i < lists.length; ++i) {
if (lists[i] != null) {
q.offer(lists[i]);
}
}
while (true) { // q is not empty
ListNode minNode = q.peek();
q.poll();
currentNode.next = minNode;
currentNode = minNode;
if (q.size() == 0) break;
if (minNode.next != null) {
q.offer(minNode.next);
}
}
return falseHead.next;
}
}