最小栈/设计getMin功能的栈

题目:设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。

  • push(x) —— 将元素 x 推入栈中。
  • pop() —— 删除栈顶的元素。
  • top() —— 获取栈顶元素。
  • getMin() —— 检索栈中的最小元素。

提示:poptop 和 getMin 操作总是在 非空栈 上调用

思路:

代码:

 1 /**
 2  * initialize your data structure here.
 3  */
 4 var MinStack = function() {
 5 this.stack = [];
 6   this.minStack = [Infinity];
 7 };
 8 
 9 /** 
10  * @param {number} val
11  * @return {void}
12  */
13 MinStack.prototype.push = function(val) {
14  this.stack.push(val);
15   this.minStack.push(Math.min(val, this.minStack[this.minStack.length - 1]))
16 };
17 
18 /**
19  * @return {void}
20  */
21 MinStack.prototype.pop = function() {
22  this.stack.pop();
23   this.minStack.pop();
24 };
25 
26 /**
27  * @return {number}
28  */
29 MinStack.prototype.top = function() {
30 return this.stack[this.stack.length - 1];
31 };
32 
33 /**
34  * @return {number}
35  */
36 MinStack.prototype.getMin = function() {
37 return this.minStack[this.minStack.length - 1]
38 };
39 
40 /**
41  * Your MinStack object will be instantiated and called as such:
42  * var obj = new MinStack()
43  * obj.push(val)
44  * obj.pop()
45  * var param_3 = obj.top()
46  * var param_4 = obj.getMin()
47  */

 

 1 /**
 2  * return a array which include all ans for op3
 3  * @param op int整型二维数组 operator
 4  * @return int整型一维数组
 5  */
 6 function getMinStack( op ) {
 7     // write code here
 8     const stack = [];
 9     const arr = [];
10     for(let i = 0; i < op.length;i++){
11         if(op[i][0] === 1){
12             stack.push(op[i][1]);
13         }
14         if(op[i][0]===2){
15             if(!stack.length) return -1;
16             stack.pop();
17         }
18         if(op[i][0] === 3){
19             let min = Math.min(...stack);
20             arr.push(min);
21         }
22     }
23     return arr;
24 }
25 module.exports = {
26     getMinStack : getMinStack
27 };

 

posted @ 2021-05-19 20:19  icyyyy  阅读(102)  评论(0)    收藏  举报