首页 > 其他 > 详细

栈的最小值

时间:2020-03-23 09:59:18      阅读:49      评论:0      收藏:0      [点我收藏+]
2020-03-23
栈的最小值

请设计一个栈,除了常规栈支持的pop与push函数以外,还支持min函数,该函数返回栈元素中的最小值。执行push、pop和min操作的时间复杂度必须为O(1)

示例:

MinStack minStack = new MinStack();

minStack.push(-2);

minStack.push(0);

minStack.push(-3);

minStack.getMin(); --> 返回 -3.

minStack.pop();

minStack.top(); --> 返回 0.

题解:
思路1: 栈基础
栈数据格式的基本操作
/**
 * initialize your data structure here.
 */
var MinStack = function () {
  this.stack = [];
  this.index = 0;
};

/** 
 * @param {number} x
 * @return {void}
 */
MinStack.prototype.push = function (x) {
  this.stack[this.index++] = x; // 最后一项插入
};

/**
 * @return {void}
 */
MinStack.prototype.pop = function () {
  this.stack.length = this.index - 1; // 通过length减小删除最后一项
  this.index--;
};

/**
 * @return {number}
 */
MinStack.prototype.top = function () { // 返回最后一项
  return this.stack[this.index - 1];
};

/**
 * @return {number}
 */
MinStack.prototype.getMin = function () { // 获取最小值
  return Math.min(...this.stack);
};

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

 

栈的最小值

原文:https://www.cnblogs.com/lanpang9661/p/12550169.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!