155. Min Stack
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,代码如下:
1 public class MinStack { 2 Stack<Integer> s; 3 int min = Integer.MAX_VALUE; 4 /** initialize your data structure here. */ 5 public MinStack() { 6 s = new Stack<Integer>(); 7 s.push(min); 8 } 9 10 public void push(int x) { 11 min = s.peek(); 12 if(min>x) min = x; 13 s.push(x); 14 s.push(min); 15 } 16 17 public void pop() { 18 s.pop(); 19 min = s.pop(); 20 } 21 22 public int top() { 23 min=s.pop(); 24 int top = s.peek(); 25 s.push(min); 26 return top; 27 } 28 29 public int getMin() { 30 return s.peek(); 31 } 32 } 33 34 /** 35 * Your MinStack object will be instantiated and called as such: 36 * MinStack obj = new MinStack(); 37 * obj.push(x); 38 * obj.pop(); 39 * int param_3 = obj.top(); 40 * int param_4 = obj.getMin(); 41 */
后来看了答案,发现其实不用占用那么多的内存,代码如下:
1 public class MinStack { 2 Stack<Integer> s; 3 int min; 4 /** initialize your data structure here. */ 5 public MinStack() { 6 s = new Stack<Integer>(); 7 min = Integer.MAX_VALUE; 8 } 9 10 public void push(int x) { 11 if(x<=min){ 12 s.push(min); 13 min = x; 14 } 15 s.push(x); 16 } 17 18 public void pop() { 19 if(s.pop()==min){ 20 min = s.pop(); 21 } 22 } 23 24 public int top() { 25 return s.peek(); 26 } 27 28 public int getMin() { 29 return min; 30 } 31 } 32 33 /** 34 * Your MinStack object will be instantiated and called as such: 35 * MinStack obj = new MinStack(); 36 * obj.push(x); 37 * obj.pop(); 38 * int param_3 = obj.top(); 39 * int param_4 = obj.getMin(); 40 */