chencl1986 / Blog

Welcome to lee's blog.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

LeetCode题解:155. 最小栈,单个栈+对象存储,JavaScript,详细注释

chencl1986 opened this issue · comments

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

解题思路:

  1. 使用一个栈,每个元素存储一个对象或数组,其中保存当前栈的值和最小值。
  2. 每次有值入栈时,存储当前值,在对比之前存储的最小值与当前值的大小,取较小值存储。
/**
 * @param {number} x
 * @return {void}
 */
MinStack.prototype.push = function(x) {
  // 如果当前栈为空,则直接存储
  if (!this.stack.length) {
    this.stack.push({
      value: x,
      min: x,
    });
  } else {
    // 对比当前最小值,进行存储
    this.stack.push({
      value: x,
      min: Math.min(x, this.stack[this.stack.length - 1].min),
    });
  }
};

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

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

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