LeetCode 剑指 Offer 30. 包含 min 函数的栈(辅助栈)—— JavaScript

题链接:https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof/

题描述:

在这里插入图片描述

解题思路:

栈 A 用于正常存储所有元素,栈 B 用于存储最小元素。

push():
(1)将 x 压入 A
(2)如果 B 为空或者 B 的栈顶元素大于等于 x 则将 x 压入 B
pop():
(1)移除 A 的栈顶元素
(2)如果该元素等于 B 的栈顶元素,则移除 B 的栈顶元素
top():
(1)返回 A 的栈顶元素
min():
(1)返回 B 的栈顶元素

代码实现

var MinStack = function() {
    this.a = [];
    this.b = [];
};

/** 
 * @param {number} x
 * @return {void}
 */
MinStack.prototype.push = function(x) {
    if (this.b.length == 0) {
        this.b.push(x);
    } else {
        let t = this.b.pop();
        this.b.push(t);
        if (t >= x) {
            this.b.push(x);
        }
    }
    this.a.push(x);
};

/**
 * @return {void}
 */
MinStack.prototype.pop = function() {
    let t = this.b.pop();
    if (this.a.pop() != t) {
        this.b.push(t);
    }
};

/**
 * @return {number}
 */
MinStack.prototype.top = function() {
    let t = this.a.pop();
    this.a.push(t);
    return t;
};

/**
 * @return {number}
 */
MinStack.prototype.min = function() {
    let t = this.b.pop();
    this.b.push(t);
    return t;
};

在这里插入图片描述

时间复杂度:O(1)
空间复杂度:O(n)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值