Java [Leetcode 155]Min Stack
2016-02-22 10:42
411 查看
题目描述:
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.
解题思路:
主要是怎么保存最小值这个问题,每次在向栈中添加数据时,总是和当前的最小值比较,如果比当前的最小值小,那么则把当前的最小值压入栈中,表明当前栈中的最小值为当前最小值,然后再把新的数据压入栈中。每次弹出栈顶的元素时候,将弹出的数据与当前的最小值比较,如果相等,表明已经达到当前最小值所在的位置,下面的那个数是当前栈中的最小值,将其弹出,其值为新的最小值。
代码如下:
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.
解题思路:
主要是怎么保存最小值这个问题,每次在向栈中添加数据时,总是和当前的最小值比较,如果比当前的最小值小,那么则把当前的最小值压入栈中,表明当前栈中的最小值为当前最小值,然后再把新的数据压入栈中。每次弹出栈顶的元素时候,将弹出的数据与当前的最小值比较,如果相等,表明已经达到当前最小值所在的位置,下面的那个数是当前栈中的最小值,将其弹出,其值为新的最小值。
代码如下:
class MinStack { Stack<Integer> stack = new Stack<Integer>(); int min = Integer.MAX_VALUE; public void push(int x) { if(x <= min){ stack.push(min); min = x; } stack.push(x); } public void pop() { int peek = stack.pop(); if(peek == min) min = stack.pop(); } public int top() { return stack.peek(); } public int getMin() { return min; } }
相关文章推荐
- eclipse 常用快捷键
- 深入源码-jetty加载spring-context容器
- java 常见的2种单例模式
- java中Date无法获取数据库时分秒的问题
- java程序实现短信发送(可调用免费短信接口)
- java-web总结--jsp--会话
- 加载properties文件属性的Java工具类实现
- java读取excel文件并写入另一个excel文件
- Eclipse的Jar包解压出System.js里String与Boolean定义分号可有可无吗?
- java的zip解压
- java的zip压缩
- Java的IO操作
- java并发编程系列
- struts tags
- Java反编译插件:Eclipse Class Decompiler
- Java打印和打印预览机制
- 使用Eclipse统计工程或文件的代码行数
- Java api 入门教程 之 JAVA的Random类
- Java 数组操作的10大方法
- 详解Java解析XML的四种方法【转载】