Min Stack
来源:互联网 发布:万象数据库修改工具 编辑:程序博客网 时间:2024/06/06 05:36
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.
Have you met this question in a real interview?
思路 1 : 就是多设置一个 minStack来存储一下最小值, push 和 pop 时候判断一下。
思路2 : 这个具有更小的空间复杂度, 设置一个 min 作为标记, 在 stack 里面存储 和 min 的差值。
class MinStack { Stack<Integer> s = new Stack<Integer>(); Stack<Integer> minStack = new Stack<Integer>(); public void push(int x) { s.push(x); if(minStack.isEmpty() || x <= minStack.peek()){//----- minStack.push(x); } } public void pop() { int num = s.pop(); if(num == minStack.peek()){ minStack.pop(); } } public int top() { return s.peek(); } public int getMin() { return minStack.peek(); }}
public class MinStack { long min; Stack<Long> stack;//有减法,所以用long,将数据越界考虑在内 public MinStack(){ stack=new Stack<>(); } public void push(int x) { if (stack.isEmpty()){ stack.push(0L); min=x; return; } stack.push(x-min);//Could be negative if min value needs to change if (x<min) min=x; } public void pop() { if (stack.isEmpty()) return; long pop=stack.pop(); if (pop<0) min=min-pop;//If negative, increase the min value } public int top() { long top=stack.peek(); if (top>0){ return (int)(top+min); }else{ return (int)(min); } } public int getMin() { return (int)min; }}
0 0
- min stack
- Min Stack
- Min Stack
- Min Stack
- Min Stack
- Min Stack
- Min Stack
- Min Stack
- Min Stack
- Min Stack
- Min Stack
- Min Stack
- Min Stack
- Min Stack
- Min Stack
- Min Stack
- Min Stack
- Min Stack
- 串口通信资料整理
- Maximum Subarray问题
- leetcode做题总结,动态规划II(Maximum Subarray, Maximum Product Subarray)
- LeetCode刷题笔录dungeon game
- linux ntfs磁盘挂载
- Min Stack
- Leetcode - Reverse Integer
- leetcode-3 closest
- leetcode-4sum
- leetcode-generate parentheses
- 2015-1-7
- 新浪微博数据挖掘食谱之十二: 用户篇 (批量获取用户的粉丝数和朋友数)
- leedcode做题总结,题目Find Minimum in Rotated Sorted ArrayI/II 153/154
- asp中,response.write alert()消息框提示信息显示变量值的方法