Go using only one stack


  • 0
    K

    The trick is the data structure of MinStack, record the min value in the struct to avoid the search operation

    type MinStack struct {
        Min int
        Val int
        Valid bool
        Next *MinStack
    }
    
    
    /** initialize your data structure here. */
    func Constructor() MinStack {
        return MinStack{0,0,false,nil}
    }
    
    
    func (this *MinStack) Push(x int)  {
        if this.Valid {
            min := int(math.Min(float64(x), float64(this.Min)))
            m := *this
            this.Min = min
            this.Val = x
            this.Valid = true
            this.Next = &m
        } else {
            this.Min = x
            this.Val = x
            this.Valid = true
        }
    }
    
    
    func (this *MinStack) Pop()  {
        if this.Valid {
            if this.Next != nil {
                *this = *this.Next
            } else {
                this.Val = 0
                this.Min = 0
                this.Valid = false
            }
            
        }
    }
    
    
    func (this *MinStack) Top() int {
        return this.Val
    }
    
    
    func (this *MinStack) GetMin() int {
        return this.Min
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.