题目描述
https://leetcode-cn.com/problems/min-stack/
解
type MinStack struct {
Min []int
Normal []int
}
/** initialize your data structure here. */
func Constructor() MinStack {
var r MinStack
return r
}
func (this *MinStack) Push(x int) {
this.Normal = append(this.Normal, x)
if len(this.Min) > 0 {
if this.Min[len(this.Min)-1] >= x {
this.Min = append(this.Min, x)
}
} else {
this.Min = append(this.Min, x)
}
}
func (this *MinStack) Pop() {
if len(this.Normal) > 0 {
if this.Min[len(this.Min)-1] == this.Normal[len(this.Normal)-1] {
this.Min = this.Min[:len(this.Min)-1]
}
this.Normal = this.Normal[:len(this.Normal)-1]
}
}
func (this *MinStack) Top() int {
if len(this.Normal) > 0 {
return this.Normal[len(this.Normal)-1]
}
return 0
}
func (this *MinStack) GetMin() int {
if len(this.Min) > 0 {
return this.Min[len(this.Min)-1]
}
return 0
}
/**
* Your MinStack object will be instantiated and called as such:
* obj := Constructor();
* obj.Push(x);
* obj.Pop();
* param_3 := obj.Top();
* param_4 := obj.GetMin();
*/
思路
用一个辅助就很简单了!
网友评论