实现一个栈,最开始想着用一个值作为最小值,忘记出栈操作后这个值就会丢了;后来minStack初始化的时候,直接初始化为空数组了,也会有问题;要注意的是,push操作,stack和minStack都有一次push操作
type MinStack struct {
minStack []int
stack []int
}
/** initialize your data structure here. */
func Constructor() MinStack {
return MinStack{
minStack: []int{math.MaxInt64},
stack: []int{},
}
}
func (this *MinStack) Push(val int) {
this.stack = append(this.stack, val)
//minStack元素栈顶需要是最小的
value := this.minStack[len(this.minStack)-1]
this.minStack = append(this.minStack, min(val,value))
}
func (this *MinStack) Pop() {
if len(this.stack) > 0{
this.minStack = this.minStack[:len(this.minStack)-1]
this.stack = this.stack[:len(this.stack)-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]
}
func min(a, b int)int{
if a > b{
return b
}
return a
}
/**
* 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();
*/