leetcode题解

「leetcode」155. 最小栈

思路

使用辅助栈同步保存最小元素

type MinStack struct {
    minStack []int
    stack    []int    
}


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


func (this *MinStack) Push(x int)  {
    this.stack = append(this.stack, x)

    // 最小栈始终与数据栈同步压入最小元素,
    if len(this.minStack) == 0 {
        // 最小栈为空,压入当前值
        this.minStack = append(this.minStack, x)
    } else if x < this.GetMin() { 
        // 当前值小于栈内最小值,压入当前值
        this.minStack = append(this.minStack, x)
    } else {
        // 当前值大于等于栈内最小值,重复压入栈内最小值
        this.minStack = append(this.minStack, this.GetMin())
    }    
}


func (this *MinStack) Pop()  {
    if len(this.stack) == 0 {
        return
    }
    // 数据栈与最小栈同步弹出
    this.stack = this.stack[:len(this.stack)-1]
    this.minStack = this.minStack[:len(this.minStack)-1]
}


func (this *MinStack) Top() int {
    if len(this.stack) == 0 {
        return -1
    }
    return this.stack[len(this.stack)-1]
}


func (this *MinStack) GetMin() int {
    if len(this.minStack) == 0 {
        return -1
    }
    return this.minStack[len(this.minStack)-1]
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值