描述:
設計一個支持 push,pop,top 操作,並能在常數時間內檢索到最小元素的棧。
push(x) – 將元素 x 推入棧中。
pop() – 刪除棧頂的元素。
top() – 獲取棧頂元素。
getMin() – 檢索棧中的最小元素。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
思路:
在原有的基礎上再使用一個棧來存最小數字,每次壓棧的時候對比一下,如果這個數比存最小的數字的棧的棧頂小或者等於的話,就將其壓入到這個存最小數字的棧中,在彈出的時候,如果彈出的數和最小棧的棧頂數相等的話就將其彈出
代碼:
class MinStack {
/** initialize your data structure here. */
Stack<Integer> stack1 =null;
Stack<Integer> stack2 = null;
public MinStack() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
public void push(int x) {
stack1.push(x);
if(stack2.isEmpty() || x <= stack2.peek()){
stack2.push(x);
}
}
public void pop() {
int x = stack1.pop();
//如果右邊是當前所彈出的數,就將右邊的數也彈出來
if (x == stack2.peek()) {
stack2.pop();
}
}
public int top() {
return stack1.peek();
}
public int getMin() {
return stack2.peek();
}
}