定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)
辅助栈法
type MinStack struct {
element []int
mins []int
}
/** initialize your data structure here. */
func Constructor() MinStack {
return MinStack{make([]int, 0), make([]int, 0)}
}
func (this *MinStack) Push(x int) {
this.element = append(this.element, x)
if len(this.mins) <= 0 {
this.mins = append(this.mins, x)
}else if x <= this.mins[len(this.mins)-1] {
this.mins = append(this.mins, x)
}
// fmt.Println("mins pushed: ",this.mins)
}
func (this *MinStack) Pop() {
end := len(this.element) - 1
end2 := len(this.mins) - 1
if this.element[end] == this.mins[end2] {
this.mins = this.mins[:end2]
}
this.element = this.element[0 : end]
// fmt.Println("mins poped:",this.mins)
}
func (this *MinStack) Top() int {
return this.element[len(this.element)-1]
}
func (this *MinStack) Min() int {
end := len(this.mins)-1
// fmt.Println("length: ",end)
if end <0 {
return -11
}
return this.mins[end]
}