Leetcode Note: Go - Min Stack

Min Stack - LeetCode
https://leetcode.com/problems/min-stack/

  • Go 言語で取り組んだメモ

所感

  • 今までとは異なる形式の問題がきた

回答

golang 16ms simple solution - LeetCode Discuss
https://leetcode.com/problems/min-stack/discuss/1373505/golang-16ms-simple-solution

type MinStack struct {
    elements []*MinStackElement
}

type MinStackElement struct {
    Val int
    Min int
}

func Constructor() MinStack {
    return MinStack{
        elements: make([]*MinStackElement, 0, 50),
    }
}

func (this *MinStack) Push(val int) {
    newElement := &MinStackElement{
        Val: val,
    }

    // MinStackElement の最小値を設定
    if len(this.elements) > 0 {
        prevMin := this.elements[len(this.elements) - 1].Min
        if val < prevMin {
            newElement.Min = val
        } else {
            newElement.Min = prevMin
        }
    } else {
        newElement.Min = val
    }

    // MinStack に新しい要素を追加
    this.elements = append(this.elements, newElement)
}

func (this *MinStack) Pop()  {
    this.elements = this.elements[0:len(this.elements) - 1]
}


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

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


/**
 * Your MinStack object will be instantiated and called as such:
 * obj := Constructor();
 * obj.Push(val);
 * obj.Pop();
 * param_3 := obj.Top();
 * param_4 := obj.GetMin();
 */
  • Stack の実装
  • 新鮮な感じ