面试题59 - II. 队列的最大值

2020-03-07  本文已影响0人  最尾一名

原题

https://leetcode-cn.com/problems/dui-lie-de-zui-da-zhi-lcof/

解题思路

辅助数组实现当前最大队列。

用一个 maxArray,表示当前队列中的最大队列。

代码

var MaxQueue = function() {
    this.array = new Array();
    this.maxArray = new Array();
};

/**
 * @return {number}
 */
MaxQueue.prototype.max_value = function() {
    return this.array.length ? this.maxArray[0] : -1;
};

/** 
 * @param {number} value
 * @return {void}
 */
MaxQueue.prototype.push_back = function(value) {
    this.array.push(value);
    while (this.maxArray.length && this.maxArray[this.maxArray.length-1] < value) {
        this.maxArray.pop();
    }
    this.maxArray.push(value);
};

/**
 * @return {number}
 */
MaxQueue.prototype.pop_front = function() {
    if (!this.array.length) return -1;
    const shiftElement = this.array.shift();
    if (shiftElement === this.maxArray[0]) {
        this.maxArray.shift();
    }
    return shiftElement;
};

/**
 * Your MaxQueue object will be instantiated and called as such:
 * var obj = new MaxQueue()
 * var param_1 = obj.max_value()
 * obj.push_back(value)
 * var param_3 = obj.pop_front()
 */

复杂度

上一篇 下一篇

猜你喜欢

热点阅读