LintCode-----12.带最小值操作的栈
来源:互联网 发布:neu的数据分析 编辑:程序博客网 时间:2024/06/07 04:02
1.自写
这里有坑就是关于栈为空的情况应怎么操作,我觉得这是比较省空间的
/** * Created by XQF on 2017/8/13. */public class MinStack { Stack<Integer> s1; Stack<Integer> s2; int min = Integer.MAX_VALUE; public MinStack() { s1 = new Stack<>(); s2 = new Stack<>(); } public void push(int number) { // write your code here if (number < min) { min = number; s2.push(min); } s1.push(number); } public int pop() { int temp = s1.pop(); if (temp == min) { min = s2.pop(); } return temp; } public int min() { // write your code here if (!s1.isEmpty()) { return s2.peek(); } return 0; } public static void main(String[] args) { MinStack stack = new MinStack(); stack.push(2); stack.push(1); stack.push(9); System.out.println(stack.min()); stack.pop(); System.out.println(stack.min()); stack.pop(); System.out.println(stack.min()); }}
2.九章
但是看代码也是没有判断使用min的时候是不是为空呀。
// version 1:public class MinStack { private Stack<Integer> stack; private Stack<Integer> minStack; public MinStack() { stack = new Stack<Integer>(); minStack = new Stack<Integer>(); } public void push(int number) { stack.push(number); if (minStack.isEmpty()) { minStack.push(number); } else { minStack.push(Math.min(number, minStack.peek())); } } public int pop() { minStack.pop(); return stack.pop(); } public int min() { return minStack.peek(); }}
阅读全文
0 0
- [LintCode]12.带最小值操作的栈
- LintCode-----12.带最小值操作的栈
- Lintcode 12. 带最小值操作的栈
- LintCode 带最小值操作的栈
- lintcode-带最小值操作的栈-12
- LintCode:带最小值操作的栈
- lintcode,带最小值操作的栈
- lintcode,带最小值操作的栈
- LintCode 12 带最小值操作的栈
- lintcode -- 带最小值操作的栈
- lintcode带最小值操作的栈
- LintCode练习-12. 带最小值操作的栈
- Lintcode 带最小值的栈
- LintCode-剑指Offer-(12)带最小值操作的栈
- [LintCode] 带最小值操作的栈 Min Stack
- [未解决][lintcode]带最小值操作的栈
- Google/LintCode:M-带最小值操作的栈
- (lintcode)第12题带最小值操作的栈
- Python如何在dic(字典)里面添加dic(字典) 附dic基础知识
- 编程小白的第一本python入门书
- 【机器人学】机器人开源项目KDL源码学习:(8)KDL的精髓
- Open vSwitch(OVS)相关问题
- Android Studio教程从入门到精通
- LintCode-----12.带最小值操作的栈
- 快速排序
- bugku sql注入2
- Retrofit 2.0 使用教程
- 002 Flask入门
- CodeForces 453 A.Little Pony and Expected Maximum(快速幂)
- 欢迎使用CSDN-markdown编辑器
- NOI
- 《机器学习实战》代码片段学习3 朴素贝叶斯