-
Notifications
You must be signed in to change notification settings - Fork 154
/
Copy pathmerge-k-sorted-lists.js
64 lines (54 loc) · 1008 Bytes
/
merge-k-sorted-lists.js
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
56
57
58
59
60
61
62
63
64
/**
* Merge k Sorted Lists
*
* Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
*
* Example:
*
* Input:
* [
* 1->4->5,
* 1->3->4,
* 2->6
* ]
* Output: 1->1->2->3->4->4->5->6
*
* Divide and Conquer
*
* Time complexity: O(nk Log k)
*/
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
import PriorityQueue from 'common/priority-queue';
/**
* @param {ListNode[]} lists
* @return {ListNode}
*/
const mergeKLists = lists => {
if (!lists || lists.length === 0) {
return null;
}
const dummy = new ListNode(0);
let p = dummy;
const pq = new PriorityQueue({
comparator: (a, b) => a.val - b.val,
});
// Initialize
for (let list of lists) {
pq.offer(list);
}
while (pq.size() > 0) {
p.next = pq.poll();
p = p.next;
if (p.next) {
pq.offer(p.next);
}
}
return dummy.next;
};
export { mergeKLists };