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.
//Approach 1: using two stack, Time: O(n), Space: O(n) class MinStack { Stack<Integer> s; Stack<Integer> m; /** initialize your data structure here. */ public MinStack() { s = new Stack<Integer>(); m = new Stack<Integer>(); } public void push(int x) { s.push(x); if (m.isEmpty() || x <= m.peek()) {//不要忘记判断m是否为空 m.push(x); } } public void pop() { int p = s.pop(); if (!m.isEmpty() && p == m.peek()) { m.pop(); } } public int top() { return s.peek(); } public int getMin() { return m.peek(); } } //Approach 2: using one stack, Time: O(n), Space: O(n) //思路就是记录一个global的min,每次当x小于min时,先把min入栈然后x入栈,这样当出栈的是min时,在pop一次就相当于找到之前的min class MinStack { Stack<Integer> s; int min = Integer.MAX_VALUE; /** initialize your data structure here. */ public MinStack() { s = new Stack<Integer>(); } public void push(int x) { if (x <= min) { s.push(min); min = x; } s.push(x); } public void pop() { if (s.pop() == min) { min = s.pop(); } } public int top() { return s.peek(); } public int getMin() { return min; } }