-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmin-stack.go
63 lines (52 loc) · 977 Bytes
/
min-stack.go
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
58
59
60
61
62
63
package main
import "math"
// source: https://leetcode.com/problems/min-stack/
type MinStack struct {
data []int
mins []int
}
func min(x, y int) int {
if x < y {
return x
}
return y
}
func Constructor() MinStack {
ms := MinStack{
data: []int{},
mins: []int{math.MaxInt},
}
return ms
}
func (ms *MinStack) Push(val int) {
ms.data = append(ms.data, val)
ms.mins = append(ms.mins, min(val, ms.mins[len(ms.data)-1]))
}
func (ms *MinStack) Pop() {
ms.data = ms.data[:len(ms.data)-1]
ms.mins = ms.mins[:len(ms.mins)-1]
}
func (ms *MinStack) Top() int {
return ms.data[len(ms.data)-1]
}
func (ms *MinStack) GetMin() int {
return ms.mins[len(ms.data)]
}
/**
* Your MinStack object will be instantiated and called as such:
* obj := Constructor();
* obj.Push(val);
* obj.Pop();
* param_3 := obj.Top();
* param_4 := obj.GetMin();
*/
func main() {
ms := Constructor()
ms.Push(4)
ms.Push(3)
ms.Push(8)
ms.Push(6)
ms.Push(1)
ms.Push(2)
return
}