剑指 Offer 30. 包含min函数的栈

61 阅读1分钟

定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 minpushpop 的时间复杂度都是 O(1)

示例:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.min();   --> 返回 -3.
minStack.pop();
minStack.top();      --> 返回 0.
minStack.min();   --> 返回 -2.

题解:

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

/** 
 * @param {number} x
 * @return {void}
 */
MinStack.prototype.push = function (x) {
    // 辅助栈与主栈大小相等,辅助栈每次push时判断
    // 当前值与栈顶元素那个值小push那个
    this.stack.push(x)
    this.helpStack.push(Math.min(this.helpStack[this.helpStack.length - 1], x));
};

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

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

/**
 * @return {number}
 */
MinStack.prototype.min = function () {
    return this.helpStack[this.helpStack.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()
 */

来源:力扣(LeetCode)

链接:leetcode.cn/problems/ba…

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。