155. Min Stack
来源:互联网 发布:北京和隆优化科技 编辑:程序博客网 时间:2024/05/23 14:03
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.
Seems easy but has lots of traps
Solution
class MinStack { Stack<Integer> stack = new Stack<Integer>();Stack<Integer> min = new Stack<Integer>();int minv = Integer.MAX_VALUE; /* First version int minValue = Integer.MAX_VALUE; public void push(int x){ if(x < minValue){ // this should be x <= minValue minValue = x; //don't foget this and in while loops don't forget i++ min.push(x); } stack.push(x) } this has a bug when min is empty and push a new element the min stack, right at this time minValue is the old value and cannot be updated so a new element cannot be added into the min stack */public void push(int x) {if (min.isEmpty() || min.peek() >= x) { min.push(x);}stack.push(x);}public void pop() {if (stack.isEmpty()) {return;}int a = stack.peek();int b = min.peek();if (a == b) { //at first I wrote if(stack.peek() == min.peek()) this does not work min.pop(); //becuase peek() returns Integer and you cannot use == to compare the value}stack.pop();}public int top() {if (stack.isEmpty()) {return 0;}return stack.peek();}public int getMin() {if (min.isEmpty()) {return 0;}return min.peek();}}
0 0
- Stack-----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
- 155. Min Stack
- Leetcode 155. Min Stack
- 155. Min Stack
- 155. Min Stack LeetCode
- 155. Min Stack
- [LeetCode]155. Min Stack
- 155. Min Stack
- 155. Min Stack
- 155. Min Stack
- LeetCode *** 155. Min Stack
- 【leetcode】155. Min Stack
- 判断语言环境
- 学习笔记3 Supervised Neural Networks
- Android 三大图片缓存原理、特性对比
- 学习笔记------数据结构(C语言版)栈应用 表达式求值
- 大数据IMF行动传奇 迈向SparkContext天堂之门! 探索天堂之门!
- 155. Min Stack
- 汉字转换拼音
- 使用Spring JMS收发消息
- log4j【6】(Java日志)
- 4260: Codechef REBXOR trie
- Logback 使用之 Hello (使用 gradle 构建)
- 2016蓝桥杯假期任务之《大小写转换》
- 小白知识点常用整理
- 根据常用需求设计的php图片处理类,可居中剪裁、等比缩放、创建缩略图