Level:
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.
思路分析:
使用两个栈,一个栈压入元素,另一个栈栈顶始终保存已经入栈元素中的最小值。
代码:
class MinStack {
/** initialize your data structure here. */
Stack<Integer>pushStack=new Stack<>();
Stack<Integer>minStack=new Stack<>();
public MinStack() {
}
public void push(int x) {
pushStack.push(x);
if(minStack.isEmpty()||x<=minStack.peek()){
minStack.push(x);
}
}
public void pop() {
if(!pushStack.isEmpty()){
if((int)pushStack.peek()==(int)minStack.peek()){
minStack.pop();
}
pushStack.pop();
}
}
public int top() {
if(!pushStack.isEmpty())
return pushStack.peek();
else
return -1;
}
public int getMin() {
return minStack.peek();
}
}