最小栈

作者: 7赢月 | 来源:发表于2020-05-13 17:48 被阅读0次

题目描述

https://leetcode-cn.com/problems/min-stack/


type MinStack struct {
    Min    []int
    Normal []int
}


/** initialize your data structure here. */
func Constructor() MinStack {
    var r MinStack
    return r
}
func (this *MinStack) Push(x int) {
    this.Normal = append(this.Normal, x)
    if len(this.Min) > 0 {
        if this.Min[len(this.Min)-1] >= x {
            this.Min = append(this.Min, x)
        }
    } else {
        this.Min = append(this.Min, x)
    }
}

func (this *MinStack) Pop() {
    if len(this.Normal) > 0 {
        if this.Min[len(this.Min)-1] == this.Normal[len(this.Normal)-1] {
            this.Min = this.Min[:len(this.Min)-1]
        }
        this.Normal = this.Normal[:len(this.Normal)-1]
    }
}

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

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

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


思路

用一个辅助就很简单了!

相关文章

  • LeetCode-155-最小栈

    LeetCode-155-最小栈 155. 最小栈[https://leetcode-cn.com/problem...

  • 最小栈

    设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。 push(x) -- 将元素 ...

  • 最小栈

    设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。 push(x) -- 将元素 ...

  • 最小栈

    https://leetcode-cn.com/explore/interview/card/bytedance/...

  • 最小栈

    题目描述 https://leetcode-cn.com/problems/min-stack/ 解 思路 用一个...

  • 最小栈

    题目 难度级别:简单 设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。 pu...

  • 最小栈

    题目描述 设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。 push(x) --...

  • 最小栈

    题目:MinStack minStack = new MinStack();minStack.push(-2);m...

  • 最小栈

    题目信息 设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。 push(x) ...

  • 栈系列之-获取最小值

    一、栈获取最小值算法概述 获取栈的最小值算法:可以动态的获取一个栈中元素的最小值,动态的意思是,当该栈发生push...

网友评论

      本文标题:最小栈

      本文链接:https://www.haomeiwen.com/subject/kylonhtx.html