Voyz's Studio.

LeetCode算法笔记--最小栈

字数统计: 244阅读时长: 1 min
2021/02/27 Share

LeetCode算法笔记-Day72

155. Min Stack

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

1
2
3
4
push(x) -- Push element x onto stack.  
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
getMin() -- Retrieve the minimum element in the stack.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Example:

Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

Output
[null,null,null,null,-3,null,0,-2]

Explanation
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top(); // return 0
minStack.getMin(); // return -2

最小栈

Snip20201027_1.png

Answer:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* initialize your data structure here.
*/
var MinStack = function() {
this._stack = [];
this._min_stack = [Infinity];
};

/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function(x) {
this._stack.push(x);
this._min_stack.push(Math.min(this._min_stack[this._min_stack.length-1],x)) ;
};

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

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

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

/**
* 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()
*/
CATALOG
  1. 1. LeetCode算法笔记-Day72
    1. 1.1. 155. Min Stack
    2. 1.2. 最小栈
      1. 1.2.1. Answer: