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.
题目含义:设计一个最小栈,push, pop, top, 和 getMin 方法都是常量时间
方法一:使用辅助栈
首先需要一个正常栈normal,用于栈的正常操作,然后需要一个辅助栈minval,专门用于获取最小值,具体操作如下。
import java.util.Stack; public class Solution { private Stack<Integer> values = new Stack<>(); private Stack<Integer> miniStack = new Stack<>(); public void push(int node) { values.push(node); if (miniStack.isEmpty()) miniStack.push(node); else miniStack.push(Math.min(miniStack.peek(), node)); } public void pop() { if (values.isEmpty()) return; values.pop(); miniStack.pop(); } public int top() { return values.peek(); } public int min() { return miniStack.peek(); } }
方法二:
1 class MinStack { 2 3 private Queue<Integer> p = new LinkedList<>(); 4 private Integer minValue = Integer.MAX_VALUE; 5 6 /** Initialize your data structure here. */ 7 public MinStack() { 8 } 9 10 public int getMin() { 11 12 for (int i=0;i<p.size();i++) 13 { 14 Integer value = p.poll(); 15 minValue = Math.min(minValue,value); 16 p.add(value); 17 } 18 return minValue; 19 } 20 21 /** Push element x onto stack. */ 22 public void push(int x) { 23 p.add(x); 24 for (int i=1;i<p.size();i++) 25 { 26 p.add(p.poll()); 27 } 28 } 29 30 /** Removes the element on top of the stack and returns that element. */ 31 public int pop() { 32 return p.poll(); 33 } 34 35 /** Get the top element. */ 36 public int top() { 37 return p.peek(); 38 } 39 40 /** Returns whether the stack is empty. */ 41 public boolean empty() { 42 return p.isEmpty(); 43 } 44 }