美文网首页Lintcode程序员
Lintcode12 Min Stack solution 题解

Lintcode12 Min Stack solution 题解

作者: 代码码着玩 | 来源:发表于2017-03-20 10:19 被阅读29次

    【题目描述】

    Implement a stack with min() function, which will return the smallest number in the stack.

    It should support push, pop and min operation all in O(1) cost.

    Notice:min operation will never be called if there is no number in the stack.

    实现一个带有取最小值min方法的栈,min方法将返回当前栈中的最小值。

    你实现的栈将支持push,pop 和 min 操作,所有操作要求都在O(1)时间内完成。

    注意:如果堆栈中没有数字则不能进行min方法的调用

    【题目链接】

    http://www.lintcode.com/en/problem/min-stack/

    【题目解析】

    利用两个栈结构,其中一个是主要的正常stack,满足pop(), push()的O(1)时间要求,另外一个作为辅助的minStack,仅存入min的integer。 min = Integer.parseInt(minStack.peek().toString());

    push()时,如果number >= min,则push到minStack上 pop()时,如果number == min,也从minStack上pop

    题中的例子,最终stack为[2, 3, 1], minStack为 [2, 1]

    【答案链接】

    http://www.jiuzhang.com/solutions/min-stack/

    相关文章

      网友评论

        本文标题:Lintcode12 Min Stack solution 题解

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