最小栈
题目:最小栈
设计一个支持push,pop,top操作,并能在常数时间内检索到最小元素的栈。
实现MinStack类:
- MinStack() 初始化堆栈对象。
- void push(int val) 将元素val推入堆栈。
- void pop() 删除堆栈顶部的元素。
- int top() 获取堆栈顶部的元素。
- int getMin() 获取堆栈中的最小元素。 思路很简单,我们只需要使用数组模拟栈结构每次操作时记录最小值即可,代码如下:
var MinStack = function() {
this.stack = []
this.min = Infinity
};
/**
* @param {number} val
* @return {void}
*/
MinStack.prototype.push = function(val) {
this.stack.push(val)
this.min = Math.min(...this.stack)
};
/**
* @return {void}
*/
MinStack.prototype.pop = function() {
let pop = this.stack.pop()
this.min = Math.min(...this.stack)
};
/**
* @return {number}
*/
MinStack.prototype.top = function() {
if (this.stack.length) {
return this.stack[this.stack.length - 1]
}
return null
};
/**
* @return {number}
*/
MinStack.prototype.getMin = function() {
return this.min
};
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
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
上次更新: 2025/09/05, 8:09:00