155. Min Stack - Easy
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.
M1: 用两个stack,s1 push 当前元素,s2同步 push 当前最小值,pop也同步
push(), pop(), top(), getMin() -- time: O(1), space: O(n)
class MinStack { LinkedList<Integer> stack; LinkedList<Integer> minStack; /** initialize your data structure here. */ public MinStack() { stack = new LinkedList<>(); minStack = new LinkedList<>(); } public void push(int x) { stack.push(x); if(minStack.isEmpty()) { minStack.push(x); } else { minStack.push(Math.min(x, minStack.peek())); } } public void pop() { stack.pop(); minStack.pop(); } public int top() { return stack.peek(); } public int getMin() { return minStack.peek(); } } /** * 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(); */
M2: 用一个stack,常数global min存最小值
push: 如果当前元素会改变global min,先push一个旧的global min, 更新global min,再把当前元素入栈
pop: 如果pop出的元素 = global min,再pop一次,global min = 第二次pop的数,即旧的global min
class MinStack { LinkedList<Integer> s; int globalMin; /** initialize your data structure here. */ public MinStack() { s = new LinkedList<>(); globalMin = Integer.MAX_VALUE; } public void push(int x) { if(x <= globalMin) { s.push(globalMin); globalMin = x; } s.push(x); } public void pop() { if(s.pop() == globalMin) { globalMin = s.pop(); } } public int top() { return s.peek(); } public int getMin() { return globalMin; } } /** * 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(); */
M3: 用两个stack,有大量重复元素的时候,s2可以存这样的pair <val, s1.size()> ,节约空间
class MinStack { LinkedList<Integer> stack; LinkedList<int[]> minStack; /** initialize your data structure here. */ public MinStack() { stack = new LinkedList<>(); minStack = new LinkedList<>(); } public void push(int x) { stack.push(x); if(minStack.isEmpty()) { minStack.push(new int[] {x, stack.size()}); } else { if(x < minStack.peek()[0]) { minStack.push(new int[] {x, stack.size()}); } } } public void pop() { if(stack.size() == minStack.peek()[1]) { stack.pop(); minStack.pop(); } else { stack.pop(); } } public int top() { return stack.peek(); } public int getMin() { return minStack.peek()[0]; } } /** * 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(); */