背景
力扣或者牛客用js做算法题时,当我们遇到要使用优先队列时,js是没有内置优先队列的,所以我们得自己写一个。
而这个优先队列的入列和出列的时间复杂度都得是O(logn)
代码
以下是小根堆
// 实现一个优先队列-小根堆
this.arr = [1, 2]
this.add = function (item) {
let arr = this.arr
arr.push(item)
let [index, preIndex] = [arr.length - 1, Math.floor((arr.length - 1 - 1) / 2)]
while (preIndex >= 0 && arr[index] < arr[preIndex]) {
[arr[index], arr[preIndex], index, preIndex] =
[arr[preIndex], arr[index], preIndex, Math.floor((preIndex - 1) / 2)]
}
}
this.top = function () {
let arr = this.arr
if (arr.length === 0) return undefined
else {
let [rsl,preIndex] =
[arr[arr.length - 1],Math.floor((arr.length - 1 - 1) / 2)]
while (preIndex >= 0) {
[rsl, preIndex] = [arr[preIndex], Math.floor((preIndex - 1) / 2)]
}
arr.length--
return rsl
}
}