【leetcode】155. Min Stack
来源:互联网 发布:app分发平台cms 编辑:程序博客网 时间:2024/05/23 11:49
题目要求:
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- getMin() -- Retrieve the minimum element in the stack.
- 即让你设计一个栈,支持push,pop,top和获取最小元素的操作
- 基本思想:借助一个辅助栈记为minStack,存储最小值。原来的栈记为stack。
- 当进行push操作时,如果stack为空,就把元素同时push进stack和minStack,如果stack不为空,将元素正常push进stack,然后获取minStack的栈顶元素,和即将入栈的元素进行比较,将较小者push进minStack
- 当进行pop操作时,两个栈都要pop
- 当进行top操作时,获取stack的栈顶元素即可
- 当要获取栈的最小值时,只要从minStack中获取栈顶元素即可
class MinStack { public Stack<Integer> stack = new Stack<Integer>(); public Stack<Integer> minStack = new Stack<Integer>(); public void push(int x) { if(stack.isEmpty()) { stack.push(x); minStack.push(x); }else { stack.push(x); int min = minStack.peek(); minStack.push(Math.min(x,min)); } } public void pop() { stack.pop(); minStack.pop(); } public int top() { return stack.peek(); } public int getMin() { return minStack.peek(); }}
0 0
- LeetCode 155. Min Stack
- 【LeetCode】155.Min Stack
- LeetCode 155.Min Stack
- [leetcode] 155.Min Stack
- [leetcode] 155.Min Stack
- Leetcode 155. Min Stack
- 155. Min Stack LeetCode
- [LeetCode]155. Min Stack
- LeetCode *** 155. Min Stack
- 【leetcode】155. Min Stack
- LeetCode 155. Min Stack
- leetcode-155. Min Stack
- LeetCode-155.Min Stack
- LeetCode - 155. Min Stack
- [Leetcode]155. Min Stack
- 【leetcode】155. Min Stack
- LeetCode 155. Min Stack
- [leetcode] 155. Min Stack
- 自定义RatingBar,更方便指定星星的图标、大小,间距
- 码农小汪-spring框架学习之11-Spring MVC简介
- 进制转换
- 字符编码 Unicode UTF-8,GB2312,shift-jis编码判断。
- PLSQL Developer 通过oracle客户端 连接oracle
- 【leetcode】155. Min Stack
- Cartesian k-means论文理解
- 配置 Apache 服务器支持 PHP 文件的解析
- 如何使用yarn界面查看spark job运行的情况
- ERROR 1045 (28000): Access denied for user 'hive'@'localhost' (using password: YES)
- LeetCode之20---Valid Parentheses
- java web项目搭建(spring4+springMVC+hibernate)
- 实现一个具有GetMin功能的栈
- [技术讨论]关于前几天发布的京东bug上的问题分析