Skip to content

Latest commit

 

History

History
53 lines (47 loc) · 1.04 KB

最小栈.md

File metadata and controls

53 lines (47 loc) · 1.04 KB
/**
 * initialize your data structure here.
 */
var MinStack = function () {
  // 声明一个辅助栈 用来存放 minValue
  this.stack = [];
  this.minStack = [Infinity];
};

/**
 * @param {number} val
 * @return {void}
 */
MinStack.prototype.push = function (val) {
  // 入栈 同时 minStack 每次保留的都是最新的最小元素
  this.stack.push(val);
  this.minStack.push(Math.min(val, this.minStack[this.minStack.length - 1]));
};

/**
 * @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];
};

/**
 * Your MinStack object will be instantiated and called as such:
 * var obj = new MinStack()
 * obj.push(val)
 * obj.pop()
 * var param_3 = obj.top()
 * var param_4 = obj.getMin()
 */