-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeKSortedLists.java
35 lines (33 loc) · 1004 Bytes
/
MergeKSortedLists.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
// https://leetcode.com/problems/merge-k-sorted-lists/
// #linked-list #divide-and-conquer #heap
/**
* Definition for singly-linked list. public class ListNode { int val; ListNode next; ListNode() {}
* ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val;
* this.next = next; } }
*/
class Solution {
// O(n*log(len(lists)))
public ListNode mergeKLists(ListNode[] lists) {
Comparator<ListNode> comparator =
(ListNode n1, ListNode n2) -> {
return n1.val - n2.val;
};
PriorityQueue<ListNode> pq = new PriorityQueue<>(comparator);
for (int i = 0; i < lists.length; i++) {
if (lists[i] != null) {
pq.add(lists[i]);
}
}
ListNode head = new ListNode();
ListNode tmp = head;
while (!pq.isEmpty()) {
ListNode min = pq.remove();
if (min.next != null) {
pq.add(min.next);
}
tmp.next = new ListNode(min.val);
tmp = tmp.next;
}
return head.next;
}
}