Skip to content

Commit 21df4ee

Browse files
authored
Update 1167-minimum-cost-to-connect-sticks.js
1 parent 78b951e commit 21df4ee

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed

1167-minimum-cost-to-connect-sticks.js

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,4 +124,90 @@ const connectSticks = function(sticks) {
124124
return result
125125
}
126126

127+
// another
128+
129+
/**
130+
* @param {number[]} sticks
131+
* @return {number}
132+
*/
133+
const connectSticks = function(sticks) {
134+
const pq = new PriorityQueue((a, b) => a < b)
135+
for(let e of sticks) pq.push(e)
136+
let res = 0
137+
while(pq.size() > 1) {
138+
const e1 = pq.pop()
139+
const e2 = pq.pop()
140+
pq.push(e1 + e2)
141+
res += e1 + e2
142+
}
143+
144+
return res
145+
};
146+
147+
class PriorityQueue {
148+
constructor(comparator = (a, b) => a > b) {
149+
this.heap = []
150+
this.top = 0
151+
this.comparator = comparator
152+
}
153+
size() {
154+
return this.heap.length
155+
}
156+
isEmpty() {
157+
return this.size() === 0
158+
}
159+
peek() {
160+
return this.heap[this.top]
161+
}
162+
push(...values) {
163+
values.forEach((value) => {
164+
this.heap.push(value)
165+
this.siftUp()
166+
})
167+
return this.size()
168+
}
169+
pop() {
170+
const poppedValue = this.peek()
171+
const bottom = this.size() - 1
172+
if (bottom > this.top) {
173+
this.swap(this.top, bottom)
174+
}
175+
this.heap.pop()
176+
this.siftDown()
177+
return poppedValue
178+
}
179+
replace(value) {
180+
const replacedValue = this.peek()
181+
this.heap[this.top] = value
182+
this.siftDown()
183+
return replacedValue
184+
}
127185

186+
parent = (i) => ((i + 1) >>> 1) - 1
187+
left = (i) => (i << 1) + 1
188+
right = (i) => (i + 1) << 1
189+
greater = (i, j) => this.comparator(this.heap[i], this.heap[j])
190+
swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])
191+
siftUp = () => {
192+
let node = this.size() - 1
193+
while (node > this.top && this.greater(node, this.parent(node))) {
194+
this.swap(node, this.parent(node))
195+
node = this.parent(node)
196+
}
197+
}
198+
siftDown = () => {
199+
let node = this.top
200+
while (
201+
(this.left(node) < this.size() && this.greater(this.left(node), node)) ||
202+
(this.right(node) < this.size() && this.greater(this.right(node), node))
203+
) {
204+
let maxChild =
205+
this.right(node) < this.size() &&
206+
this.greater(this.right(node), this.left(node))
207+
? this.right(node)
208+
: this.left(node)
209+
this.swap(node, maxChild)
210+
node = maxChild
211+
}
212+
}
213+
}

0 commit comments

Comments
 (0)