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

LeetCode题解:155.最小栈,使用两个栈,详细注释 #143

Open
chencl1986 opened this issue Aug 28, 2020 · 0 comments
Open

LeetCode题解:155.最小栈,使用两个栈,详细注释 #143

chencl1986 opened this issue Aug 28, 2020 · 0 comments

Comments

@chencl1986
Copy link
Owner

chencl1986 commented Aug 28, 2020

原题链接:https://leetcode-cn.com/problems/min-stack/

解题思路:

本题解参考了官方题解

  1. 使用两个栈,一个栈保存当前存入的结果,辅助栈保存每次入栈时,当前保存的最小值。
  2. 可以理解为辅助栈中保存了每次入栈操作时,当前的最小值。

复杂度分析:

时间复杂度:各操作均为O(1)
空间复杂度:O(n)

/**
 * initialize your data structure here.
 */
var MinStack = function () {
  this.stack = [];
  this.minStack = [Infinity]; // 使用无穷大,保证第一个值入栈时,一定会被存入辅助栈
};

/**
 * @param {number} x
 * @return {void}
 */
MinStack.prototype.push = function (x) {
  this.stack.push(x);
  // 每次存入一个值时,都将当前最小值与存入的值进行比较,保存较小的值。
  // 可以理解为,缓存了每次入栈操作时,当前栈的最小值。
  this.minStack.push(Math.min(this.minStack[this.minStack.length - 1], x));
};

/**
 * @return {void}
 */
MinStack.prototype.pop = function () {
  this.stack.pop();
  this.minStack.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];
};
@chencl1986 chencl1986 changed the title LeetCode题解:155.最小栈,辅助栈,官方解法,详细注释 LeetCode题解:155.最小栈,使用两个栈,详细注释 Aug 29, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant