LeetCode 剑指 Offfer 59 - II. 队列的最大值(辅助队列)—— JavaScript

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

类似题:栈的最小值(辅助栈)


题描述:


解题思路:

利用 numQueue 保存输入的变量,利用辅助队列 assQueue 维护一个递减队列,队首存放 numQueue 中的最大值。

(1)max_value:

  如果队列为空,返回 -1,否则返回 assQueue 队首元素。

(2)push_back:

  当一个新的元素 T 要进入 numQueue 时,将 assQueue 队列中比 T 小的元素出队,因为此时前面比 T 小的元素都不会成为最大值。

  然后压入 numQueue 和 assQueue。

(3)pop_front:

  如果队列为空,返回 -1,否则如果 numQueue 要出队的元素与 assQueue 队首元素相同,则 assQueue 队首元素也要出队。


代码实现:

var MaxQueue = function() {
    this.numQueue = [];
    this.assQueue = [];
};

/**
 * @return {number}
 */
MaxQueue.prototype.max_value = function() {
    if (this.assQueue.length == 0) {
        return -1;
    }
    return this.assQueue[0];
};

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

/**
 * @return {number}
 */
MaxQueue.prototype.pop_front = function() {
    if (this.numQueue.length == 0) {
        return -1;
    }
    let t = this.numQueue.shift();
    if (t == this.assQueue[0]) {
        this.assQueue.shift();
    }
    return t;
};

时间复杂度:O(1)

空间复杂度:O(n)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值