LeetCode()- 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.
思路:
題意:給出四個函數API,構造一個stack,而且能夠返回最小值
用雙棧的策略,一個用來正常的存儲,一個用來存貯最小值
注意比較的時候。peek()函數要用equals函數比較,因為彈出的是對象
代碼:
class MinStack {
Stack stack = new Stack();
Stack min = new Stack();
public void push(int x) {
if(min.isEmpty() || x <= min.peek()){
min.push(x);
}
stack.push(x);
}
public void pop() {
if(stack == null){
return;
}
if(min.peek().equals(stack.peek())){
min.pop();
}
stack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return min.peek();
}
}