Skip to content

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

Description

@chencl1986

原题链接: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];
};

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions