[LintCode] 带最小值操作的栈 Min Stack
2016-04-22 15:48
344 查看
实现一个带有取最小值min方法的栈,min方法将返回当前栈中的最小值。
你实现的栈将支持push,pop 和 min 操作,所有操作要求都在O(1)时间内完成。
样例
如下操作:push(1),pop(),push(2),push(3),min(), push(1),min() 返回 1,2,1
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.
Example
push(1)
pop() // return 1
push(2)
push(3)
min() // return 2
push(1)
min() // return 1
参考:/article/3642055.html
/article/3642055.html
你实现的栈将支持push,pop 和 min 操作,所有操作要求都在O(1)时间内完成。
样例
如下操作:push(1),pop(),push(2),push(3),min(), push(1),min() 返回 1,2,1
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.
Example
push(1)
pop() // return 1
push(2)
push(3)
min() // return 2
push(1)
min() // return 1
参考:/article/3642055.html
/article/3642055.html
public class MinStack { Stack<Integer> stack; int min; public MinStack() { stack = new Stack<Integer>(); min = 0; } public void push(int number) { if(stack.size() == 0) { stack.push(number); min = number; } else{ if(number >= min) { stack.push(number); }else { stack.push(2*number - min); min = number; } } } public int pop() { if(!stack.isEmpty()) { int temp = stack.pop(); if(temp < min) { int num = min; min = 2*min - temp; temp = num; } return temp; }else { return min; } } public int min() { return min; } }
相关文章推荐
- 【使用Modern UI快速开发WPF应用】
- 海量数据去重排序--bitmap(位图法)在java中的实现的两种方法
- 【转】Android之drawable state各个属性详解
- 服务器实现处理GET和POST
- 每日站立会议(五)
- ORACLE的字符串操作函数
- Java反射机制可以动态修改实例中final修饰的成员变量吗?
- 推荐!Sublime Text 最佳插件列表
- Failed to set () user defined inspected property on (UIButton): [<UIButton 0x7fe5586efeb0> setValue:
- Apache Httpd负载均衡Tomcat并实现Session Sticky和Session Cluster 推荐
- 客户端和服务端在同一台机器上,wireshark如何实现抓包
- xcode 菜单翻译
- Mongodb连接详解
- Windows环境安装Linux系统及jdk部署
- WCF部署IIS所遇到的问题 (解决404.17、.svc无法读取问题)
- 书单计划(关于技术、思想、个人)
- android模拟小米天气view(上)
- 网闸与防火墙的区别
- GIMP 创建arm LCD上显示的图片
- C++内存管理