Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

155. 最小栈 #23

Open
Geekhyt opened this issue Feb 4, 2021 · 0 comments
Open

155. 最小栈 #23

Geekhyt opened this issue Feb 4, 2021 · 0 comments
Labels

Comments

@Geekhyt
Copy link
Owner

Geekhyt commented Feb 4, 2021

原题链接

辅助栈

  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)
@Geekhyt Geekhyt added the 简单 label Jun 4, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant