LeetCode-最小棧

設計一個支持 push,pop,top 操做,並能在常數時間內檢索到最小元素的棧。golang

  • push(x) -- 將元素 x 推入棧中。
  • pop() -- 刪除棧頂的元素。
  • top() -- 獲取棧頂元素。
  • getMin() -- 檢索棧中的最小元素。

示例:數據結構

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> 返回 -3.
minStack.pop();
minStack.top();      --> 返回 0.
minStack.getMin();   --> 返回 -2.
複製代碼

解法:app

大概思路是使用維護兩個棧,一個保存數據,一個保存最小值的索引。ui

type MinStack struct {
    data []interface{}
    minIndex []int
}


/** initialize your data structure here. */
func Constructor() MinStack {
    var instance MinStack
    return instance
}


func (this *MinStack) Push(x int)  {
    this.data = append(this.data, x)
    if len(this.minIndex) == 0 {
        this.minIndex = append(this.minIndex, 0)
    } else {
        //當前最小值比新值大
        if this.data[this.minIndex[len(this.minIndex) - 1]].(int) > x {
            //當前最小值索引壓入minIndex
            this.minIndex = append(this.minIndex, len(this.data) - 1)
        } 
    }
}


func (this *MinStack) Pop()  {
    length := len(this.data)
    currentMinIndex := length - 1
    
    if currentMinIndex == this.minIndex[len(this.minIndex) - 1] {
        this.minIndex = this.minIndex[:len(this.minIndex) - 1]
    }
    
    this.data = this.data[:len(this.data) - 1]
}


func (this *MinStack) Top() int {
    return this.data[len(this.data) - 1].(int)
}


func (this *MinStack) GetMin() int {
    return this.data[this.minIndex[len(this.minIndex) - 1]].(int)
}


/** * 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(); */
複製代碼

參考this

相關文章
相關標籤/搜索