Skip to content

Commit a7fa5c0

Browse files
authored
Update 23-merge-k-sorted-lists.js
1 parent 4fd8ec1 commit a7fa5c0

File tree

1 file changed

+100
-0
lines changed

1 file changed

+100
-0
lines changed

23-merge-k-sorted-lists.js

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,3 +33,103 @@ function merge(lists, l, r) {
3333
head.next = left ? left : right
3434
return dummy.next
3535
}
36+
37+
// another
38+
39+
/**
40+
* Definition for singly-linked list.
41+
* function ListNode(val, next) {
42+
* this.val = (val===undefined ? 0 : val)
43+
* this.next = (next===undefined ? null : next)
44+
* }
45+
*/
46+
/**
47+
* @param {ListNode[]} lists
48+
* @return {ListNode}
49+
*/
50+
const mergeKLists = function(lists) {
51+
if(lists == null || lists.length === 0) return null
52+
const dummy = new ListNode()
53+
let head = dummy
54+
const pq = new PriorityQueue((a, b) => a.val < b.val)
55+
for(let list of lists) {
56+
while(list) {
57+
pq.push(list)
58+
list = list.next
59+
}
60+
}
61+
while(!pq.isEmpty()) {
62+
const pop = pq.pop()
63+
head.next = new ListNode(pop.val)
64+
head = head.next
65+
}
66+
return dummy.next
67+
};
68+
69+
class PriorityQueue {
70+
constructor(comparator = (a, b) => a > b) {
71+
this.heap = []
72+
this.top = 0
73+
this.comparator = comparator
74+
}
75+
size() {
76+
return this.heap.length
77+
}
78+
isEmpty() {
79+
return this.size() === 0
80+
}
81+
peek() {
82+
return this.heap[this.top]
83+
}
84+
push(...values) {
85+
values.forEach((value) => {
86+
this.heap.push(value)
87+
this.siftUp()
88+
})
89+
return this.size()
90+
}
91+
pop() {
92+
const poppedValue = this.peek()
93+
const bottom = this.size() - 1
94+
if (bottom > this.top) {
95+
this.swap(this.top, bottom)
96+
}
97+
this.heap.pop()
98+
this.siftDown()
99+
return poppedValue
100+
}
101+
replace(value) {
102+
const replacedValue = this.peek()
103+
this.heap[this.top] = value
104+
this.siftDown()
105+
return replacedValue
106+
}
107+
108+
parent = (i) => ((i + 1) >>> 1) - 1
109+
left = (i) => (i << 1) + 1
110+
right = (i) => (i + 1) << 1
111+
greater = (i, j) => this.comparator(this.heap[i], this.heap[j])
112+
swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])
113+
siftUp = () => {
114+
let node = this.size() - 1
115+
while (node > this.top && this.greater(node, this.parent(node))) {
116+
this.swap(node, this.parent(node))
117+
node = this.parent(node)
118+
}
119+
}
120+
siftDown = () => {
121+
let node = this.top
122+
while (
123+
(this.left(node) < this.size() && this.greater(this.left(node), node)) ||
124+
(this.right(node) < this.size() && this.greater(this.right(node), node))
125+
) {
126+
let maxChild =
127+
this.right(node) < this.size() &&
128+
this.greater(this.right(node), this.left(node))
129+
? this.right(node)
130+
: this.left(node)
131+
this.swap(node, maxChild)
132+
node = maxChild
133+
}
134+
}
135+
}

0 commit comments

Comments
 (0)