LeetCode -- Min Stack
2016-02-15 10:32
363 查看
Question:
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.
Analysis:
设计一个栈,它能够支持push, pop, top操作,并且能够在常数时间内检索到最小的元素。
solution1: 利用Java内置的Stack类,并且设置一个格外的栈,当每次有元素进栈时都判断是否是额外栈的最小元素。这样当求最小元素时直接peek额外栈的栈顶元素即可。
solution2: 不适用Java内置的Stack类,每个栈节点维护一个最小值(是当前节点至栈底的最小值),其余操作与上面相同,只不过push,pop等基本操作要自己简单的实现一下。
Answer:
Solution1:
Solution2:
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.
Analysis:
设计一个栈,它能够支持push, pop, top操作,并且能够在常数时间内检索到最小的元素。
solution1: 利用Java内置的Stack类,并且设置一个格外的栈,当每次有元素进栈时都判断是否是额外栈的最小元素。这样当求最小元素时直接peek额外栈的栈顶元素即可。
solution2: 不适用Java内置的Stack类,每个栈节点维护一个最小值(是当前节点至栈底的最小值),其余操作与上面相同,只不过push,pop等基本操作要自己简单的实现一下。
Answer:
Solution1:
class MinStack { private Stack<Integer> stack = new Stack<Integer>(); private Stack<Integer> minStack = new Stack<Integer>(); public void push(int x) { if(minStack.isEmpty() || x <= minStack.peek()) //if x is the minimum value minStack.push(x); stack.push(x); } public void pop() { if(stack.peek().equals(minStack.peek())) //if the pop value is the minimum minStack.pop(); stack.pop(); } public int top() { return stack.peek(); } public int getMin() { return minStack.peek(); } }
Solution2:
class MinStack { StackNode top = null; public void push(int x) { if(top == null) { top = new StackNode(x); top.min = x; top.next = null; } else { StackNode node = new StackNode(x); if(x < top.min) node.min = x; else node.min = top.min; node.next = top; top = node; } } public void pop() { if(top != null) top = top.next; } public int top() { if(top != null) return top.val; else return 0; } public int getMin() { if(top != null) return top.min; else return 0; } } class StackNode { int val; int min; //store the min utile this node StackNode next; public StackNode(int x) { val = x; } }
相关文章推荐
- 【JSTL】--读取实体成员变量吗?--drp212
- Linux学习笔记:ls命令
- 【转载】为什么无线信号(RSSI)是负值
- Android Studio获取SHA1(获取SHA1的通用方法)
- [solr] - spell check
- 有用的blog
- Linux do some cool things or funny things
- C# socket nat 映射 网络 代理 转发
- [solr] - Facet - autocomplete
- Core Image 和视频
- python模块--random
- oracle14连接NL Exception was generated异常问题
- 自动删除Mysql备份(数组+for)
- 基于python yield机制的异步操作同步化编程模型
- 学习新东西的唯一方法
- LintCode : 生成括号
- 利用python抓取京东的数据
- Spring 框架
- linux安装文件
- eclipse导入源码