剑指 Offer 59 - II. 队列的最大值

118 阅读1分钟

剑指 Offer 59 - II. 队列的最大值

若队列为空,pop_front 和 max_value 需要返回 -1

代码实现,这里注意到 当队列为空时候,求max_value应该返回-1 求pop_front返回-1,其中[].shift()返回的是undefined

var MaxQueue = function() {
    this.arr = []
};
MaxQueue.prototype.max_value = function() {
    if(this.arr.length === 0){
        return -1
    }
   return  Math.max(...this.arr)
};
MaxQueue.prototype.push_back = function(value) {
    this.arr.push(value)
};
MaxQueue.prototype.pop_front = function() {
    var first = this.arr.shift()
    if(first === undefined){
        return -1
    }else{
        return first
    }
};