Leetcode 155 Min Stack
来源:互联网 发布:无网络小游戏 编辑:程序博客网 时间:2024/06/18 04:18
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.
Example:
MinStack minStack = new MinStack();minStack.push(-2);minStack.push(0);minStack.push(-3);minStack.getMin(); --> Returns -3.minStack.pop();minStack.top(); --> Returns 0.minStack.getMin(); --> Returns -2.
实现一个min stack
我写的比较基础 但是 time超了
public class MinStack { private int count; List<Integer> list; /** initialize your data structure here. */ public MinStack() { list = new LinkedList<Integer>(); count = 0; } public void push(int x) { count++; list.add(x); } public void pop() { list.remove(count-1); count--; } public int top() { return list.get(count-1); } public int getMin() { int min = list.get(0); for(int i = 0;i<count;i++){ if(list.get(i)<min){ min = list.get(i); } } return min; }}/** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(x); * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.getMin(); */
然后我发现其实是自己傻了 = =可以用stack来实现的啊========
public class MinStack { long min; Stack<Long> stack; public MinStack(){ stack=new Stack<>(); } public void push(int x) { if (stack.isEmpty()){ stack.push(0L); min=x; }else{ stack.push(x-min);//Could be negative if min value needs to change 存入的是与最小值的差值 if (x<min) min=x;//我觉得这里最聪明的地方在于减少了循环 在push的时候就检查比较最小值 } } public void pop() { if (stack.isEmpty()) return; long pop=stack.pop(); if (pop<0) min=min-pop;//如果弹出去的是负数 说明压栈的时候 这个value小于当时的min 也就是弹出去的是当前最小值 那么原来的最小值就是 min - pop } 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
- LeetCode(155) Min Stack
- [leetcode 155] Min Stack
- leetCode #155 Min Stack
- LeetCode[155]Min Stack
- leetcode-155 Min Stack
- leetcode 155 Min Stack
- LeetCode[155]-Min Stack
- leetcode 155:Min Stack
- LeetCode---(155)Min Stack
- leetcode-155-Min Stack
- leetcode 155: Min Stack
- [leetcode] #155 Min Stack
- LeetCode 155 Min Stack
- 【LEETCODE】155-Min Stack
- LeetCode 155:Min Stack
- [leetcode 155] Min Stack
- leetcode 155: Min Stack
- 【leetcode】【155】Min Stack
- Leetcode 2 Add Two Numbers
- java I/O之装饰设计模式
- N子棋project小记
- java随手记
- 碎片到碎片 碎片到活动 之间的通信
- Leetcode 155 Min Stack
- 百度地图 画线设置折线点 另一方法
- 【BZOJ 1024】 [SCOI2009]生日快乐
- 有限域上的逆运算
- 回文排列(Palindrome Permutation)
- jsp+servlet 建立自己的第一个网站
- 组合模式
- Leetcode 530 Minimum Absolute Difference in BST
- BCE0004: Ambiguous reference 'preview': CameraMotionBlurEditor.preview, UnityEditor.Editor.preview.