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.
// constructor 后面要有括号
// java中取最大的那个数字是peek(偷看一次不拿出来)不是peak(顶峰,这个用pop代替了)
// minStack.isEmpty() 的E是大写
class MinStack { private Stack minStack; private Stack Stack; public MinStack(){ minStack = new Stack(); Stack = new Stack(); } 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() { minStack.pop(); Stack.pop(); } public int top() { minStack.peek(); return Stack.peek(); } public int getMin() { return minStack.peek(); } }