題目
設計一個支持 push,pop,top 操作,並能在常數時間內檢索到最小元素的棧。
push(x) -- 將元素 x 推入棧中。
pop() -- 刪除棧頂的元素。
top() -- 獲取棧頂元素。
getMin() -- 檢索棧中的最小元素。
代碼
class MinStack {
private Stack<Integer> dataStack = new Stack<Integer>();
private Stack<Integer> minStack = new Stack<Integer>();
public MinStack() {
}
public void push(int x) {
dataStack.push(x);
if(!minStack.isEmpty()){
if(getMin() <= x){
minStack.push(getMin());
}else{
minStack.push(x);
}
}else{
minStack.push(x);
}
}
public void pop() {
dataStack.pop();
minStack.pop();
}
public int top() {
return dataStack.peek();
}
public int getMin() {
return minStack.peek();
}
}