Skip to content

155. 最小栈 #23

Open
Open
@Geekhyt

Description

@Geekhyt

原题链接

辅助栈

  1. stack 支持常规的 push、pop、top 操作。
  2. 定义一个辅助栈 resStack ,将最小值一直保持在栈顶,来支持常数时间复杂度获取。
const MinStack = function() {
    this.stack = [];
    this.resStack = [Infinity];
};

MinStack.prototype.push = function(x) {
    this.stack.push(x);
    this.resStack.push(Math.min(this.resStack[this.resStack.length - 1], x));
};

MinStack.prototype.pop = function() {
    this.stack.pop();
    this.resStack.pop();
};

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

MinStack.prototype.getMin = function() {
    return this.resStack[this.resStack.length - 1];
};
  • 时间复杂度: O(1)
  • 空间复杂度: O(n)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions