forked from yunyinl/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeKSortedLists.java
More file actions
55 lines (47 loc) · 1.28 KB
/
Copy pathMergeKSortedLists.java
File metadata and controls
55 lines (47 loc) · 1.28 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
46
47
48
49
50
51
52
53
54
55
package amazon;
import entity.ListNode;
import java.util.Comparator;
import java.util.PriorityQueue;
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
/**
* Created by anduo on 17-3-13.
*/
public class MergeKSortedLists {
public ListNode mergetKLists(ListNode[] lists) {
if (lists == null || lists.length == 0) return null;
PriorityQueue<ListNode> queue = new PriorityQueue<>(lists.length, new Comparator<ListNode>() {
@Override
public int compare(ListNode o1, ListNode o2) {
if (o1.val < o2.val) {
return -1;
} else if (o1.val == o2.val) {
return 0;
} else {
return 1;
}
}
});
ListNode dummy = new ListNode(0);
ListNode head = dummy;
for (ListNode node : lists) {
if (node != null) {
queue.add(node);
}
}
while (!queue.isEmpty()) {
head.next = queue.poll();
head = head.next;
if (head.next != null) {
queue.add(head.next);
}
}
return dummy.next;
}
}