class MaxQueue {
constructor() {
this.queue = []
this.max = []
}
enqueue(el) {
this.queue.push(el)
while(this.max.length && this.max[this.max.length - 1] < el) {
this.max.pop()
}
this.max.push(el)
}
dequeue() {
if(!this.queue.length) {
return -Infinity
}
const el = this.queue.shift()
if(el === this.max[0]) {
this.max.shift()
}
return el
}
getMax() {
if(this.max.length) {
return this.max[0]
}
return -Infinity
}
}
const maxQueue = new MaxQueue()
maxQueue.enqueue(1)
maxQueue.enqueue(2)
maxQueue.enqueue(-1)
console.log(maxQueue.getMax())
console.log(maxQueue.dequeue())
console.log(maxQueue.getMax())
console.log(maxQueue.dequeue())
console.log(maxQueue.getMax())
console.log(maxQueue.dequeue())
console.log(maxQueue.getMax())
可视化版本。
https://max-queue.vercel.app/
标签:el,maxQueue,console,log,实现,max,JS,getMax,MaxQueue From: https://www.cnblogs.com/zjy4fun/p/17686223.html