LeetCode 155. 最小栈
题目描述
✅ 155. 最小栈
思路分析
双栈法
参考代码
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
type MinStack struct {
stack []int // 正常栈
minStack []int // 最小值栈
}
// 构造函数
func Constructor() MinStack {
return MinStack{
stack: []int{},
minStack: []int{},
}
}
// 入栈操作
func (this *MinStack) Push(x int) {
this.stack = append(this.stack, x)
// 如果 minStack 为空或当前值更小,则入最小栈
if len(this.minStack) == 0 || x <= this.minStack[len(this.minStack)-1] {
this.minStack = append(this.minStack, x)
} else {
// 否则重复推入当前最小值,保持栈同步
this.minStack = append(this.minStack, this.minStack[len(this.minStack)-1])
}
}
// 出栈操作
func (this *MinStack) Pop() {
if len(this.stack) == 0 {
return
}
this.stack = this.stack[:len(this.stack)-1]
this.minStack = this.minStack[:len(this.minStack)-1]
}
// 获取栈顶元素
func (this *MinStack) Top() int {
return this.stack[len(this.stack)-1]
}
// 获取最小值
func (this *MinStack) GetMin() int {
return this.minStack[len(this.minStack)-1]
}
1
write your code here
CC BY-NC-SA 4.0
许可协议,转载请注明出处!
本博客所有文章除特别声明外,均采用