CodeTheWorld / CodeTheWorld.github.io

MIT License
1 stars 1 forks source link

最小栈-leetcode - CodeTheWorld #27

Open CodeTheWorld opened 5 years ago

CodeTheWorld commented 5 years ago

https://codetheworld.github.io/2018/11/19/leetcode-155-min-stack.html

nber1994 commented 5 years ago

牛逼

nber1994 commented 5 years ago

存差值,如果差值小于零说明要更新min,而该元素存储的也就是上一个min和本元素的差值,所以可以按照这个差值还原本元素入栈之前的最小值,卧槽

nber1994 commented 5 years ago
type MinStack struct {
        stack []int
        min   int
}

/** initialize your data structure here. */
func Constructor() MinStack {
        return MinStack{[]int{}, 0}
}

func (this *MinStack) Push(x int) {
        if len(this.stack) == 0 {
                this.min = x
        }
        this.stack = append(this.stack, x-this.min)
        if x < this.min {
                this.min = x
        }
}

func (this *MinStack) Pop() {
        tail := this.stack[len(this.stack)-1]
        this.stack = this.stack[:len(this.stack)-1]
        if tail < 0 {
                this.min = this.min - tail
        }
}

func (this *MinStack) Top() int {
        tail := this.stack[len(this.stack)-1]
        if tail >= 0 {
                return tail + this.min
        } else {
                return this.min
        }
}

func (this *MinStack) GetMin() int {
        return this.min
}

/**
* 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();
 */