# 最小栈 (opens new window)

重点在于:"能在常数时间内检索到最小元素的栈", 所以除了存储栈外还要另设一个"最小栈"

  • 难度:Easy
  • 标签:栈

# 刷题思路

  • [x] 存储栈 + 最小栈
  • [ ] xx

# 方法 1

/**
 * initialize your data structure here.
 */
var MinStack = function() {
    this.stack = []
    this.minStack = []
};

/** 
 * @param {number} x
 * @return {void}
 */
MinStack.prototype.push = function(x) {
    this.stack.push(x)
    if (this.minStack.length === 0) {
        this.minStack.push(x)
    } else {
        this.minStack.push(Math.min(x, this.getMin()))
    }
};

/**
 * @return {void}
 */
MinStack.prototype.pop = function() {
    this.minStack.pop()
    return this.stack.pop()
};

/**
 * @return {number}
 */
MinStack.prototype.top = function() {
    return this.stack[this.stack.length-1]
};

/**
 * @return {number}
 */
MinStack.prototype.getMin = function() {
    return this.minStack[this.minStack.length-1]
};

# 方法 2

  • 复杂度:
    • 时间 O()
    • 空间 O()

JS刷题记录 Leetcode-js (opens new window) 每周都会更新刷题心得或者题解, 你的点赞或 star 都将助力我产出更好内容~