题解
思路:两个栈,一个最小栈,push的时候如果不比最小的小,那么最小栈就接着push这个最小的数,这样就和pop形成了同步
代码
package main import "math" type MinStack struct { min []int stack []int } func Constructor() MinStack { return MinStack{} } func (this *MinStack) Push(val int) { if val < this.GetMin() { this.min = append(this.min, val) } else { this.min = append(this.min, this.GetMin()) } this.stack = append(this.stack, val) } func (this *MinStack) Pop() { if len(this.stack) == 0 { return } this.stack = this.stack[0 : len(this.stack)-1] this.min = this.min[0 : len(this.min)-1] } func (this *MinStack) Top() int { if len(this.stack) == 0 { return 0 } return this.stack[len(this.stack)-1] } func (this *MinStack) GetMin() int { if len(this.min) == 0 { return math.MaxInt32 } else { return this.min[len(this.min)-1] } } /** * 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() { }