剑指Offer(包含min函数的栈)

148 阅读1分钟

包含min函数的栈

image.png

题目分析

  • 本题要求实现一个包含min函数的栈结构并且要求min,push,pop的时间复杂度要在常量级,所以我们不能在函数中进行排序操作。我们引入一个辅助栈用来维护主栈中的最小值,每次主栈插入数据的时候同时向辅助栈中插入主栈中的最小值,每次主栈弹出数据时辅助栈也弹出当前最小值。这样辅助栈中的栈顶元素就是当前主栈中的最小元素。

代码

/**
 * 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);
    this.minStack.push(Math.min(x, this.min()));
};

/**
 * @return {void}
 */
MinStack.prototype.pop = function () {
    const { stack, minStack } = this;
    if (!stack.length) return;
    this.stack.pop();
    this.minStack.pop();
};

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

/**
 * @return {number}
 */
MinStack.prototype.min = function () {
    const { minStack } = this;
    if (!minStack.length) return Infinity;
    return minStack[minStack.length - 1];
};

/**
 * Your MinStack object will be instantiated and called as such:
 * var obj = new MinStack()
 * obj.push(x)
 * obj.pop()
 * var param_3 = obj.top()
 * var param_4 = obj.min()
 */