[LeetCode] Min Stack
2015-11-07 15:49
381 查看
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(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 { // normal stack Stack<Integer> st = new Stack<Integer>(); // min value stack Stack<Integer> stm = new Stack<Integer>(); public void push(int x) { st.push(x); if (stm.isEmpty() || stm.peek() >= x) stm.push(x); } public void pop() { int peek = st.peek(); st.pop(); if (peek <= stm.peek()) stm.pop(); } public int top() { return st.peek(); } public int getMin() { return stm.peek(); } }
相关文章推荐
- 结构体定义 typedef struct 用法
- poj 2236 Wireless Network(并查集)
- post 登录需要token
- python之poplib模块下载并解析邮件
- Android过度绘制深度优化---View提前绘制
- Java实现将两个数之和用标准形式输出
- Java线程,多线程,线程同步,以及Java回调线程,还有难懂的synchronized
- [C++] const object
- 牛刀小试(01)——像素翻转
- FTP的PORT(主动模式)和PASV(被动模式)
- poj 2104 (主席树)
- Mac的QQ不能截图了怎么办?
- [leetcode 190] Reverse Bits
- NSDate和NSString的相互转换
- UML之交互图(顺序图和协作图)
- 一个C#版本的Directx函数j介绍文档
- 第一次上传项目到gitHub
- WIFI能ping通所有网络,却不能上网解决方案
- C++复习笔记
- 排序算法(四):堆排序