温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Lintcode12 Min Stack solution 题解

发布时间:2020-06-13 14:08:20 来源:网络 阅读:319 作者:coderer 栏目:软件技术

题目描述】

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/


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI