-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path155.min-stack.go
More file actions
58 lines (47 loc) · 1.11 KB
/
155.min-stack.go
File metadata and controls
58 lines (47 loc) · 1.11 KB
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
48
49
50
51
52
53
54
55
56
57
/*
* @lc app=leetcode id=155 lang=golang
*
* [155] Min Stack
*/
// 创建一个辅助栈空间,维持栈的最小元素
// 入栈值比当前值小,则该值入栈,否则最小值入栈
type MinStack struct {
Data []int
Min []int
}
/** initialize your data structure here. */
func Constructor() MinStack {
return MinStack{
[]int{},
[]int{},
}
}
func (this *MinStack) Push(x int) {
this.Data = append(this.Data,x)
if len(this.Min) == 0{
this.Min = append(this.Min,x)
}else if this.Min[len(this.Min)-1] > x{ // 非空
this.Min = append(this.Min,x)
}else{
this.Min = append(this.Min,this.Min[len(this.Min)-1])
}
}
// 不考虑空pop和空top
func (this *MinStack) Pop() {
this.Data = this.Data[:len(this.Data)-1]
this.Min = this.Min[:len(this.Min)-1]
}
func (this *MinStack) Top() int {
return this.Data[len(this.Data)-1]
}
func (this *MinStack) GetMin() int {
return this.Min[len(this.Min)-1]
}
/**
* Your MinStack object will be instantiated and called as such:
* obj := Constructor();
* obj.Push(x);
* obj.Pop();
* param_3 := obj.Top();
* param_4 := obj.GetMin();
*/