「leetcode」155. 最小栈
思路
使用辅助栈同步保存最小元素
type MinStack struct {
minStack []int
stack []int
}
/** initialize your data structure here. */
func Constructor() MinStack {
return MinStack{
minStack: []int{},
stack: []int{},
}
}
func (this *MinStack) Push(x int) {
this.stack = append(this.stack, x)
// 最小栈始终与数据栈同步压入最小元素,
if len(this.minStack) == 0 {
// 最小栈为空,压入当前值
this.minStack = append(this.minStack, x)
} else if x < this.GetMin() {
// 当前值小于栈内最小值,压入当前值
this.minStack = append(this.minStack, x)
} else {
// 当前值大于等于栈内最小值,重复压入栈内最小值
this.minStack = append(this.minStack, this.GetMin())
}
}
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 {
if len(this.stack) == 0 {
return -1
}
return this.stack[len(this.stack)-1]
}
func (this *MinStack) GetMin() int {
if len(this.minStack) == 0 {
return -1
}
return this.minStack[len(this.minStack)-1]
}