原题链接在这里: https://leetcode.com/problems/min-stack/
push(), pop(),top() 都是原有的API, 关键是getMin(). 可以用另一个stack, min_stk来维护这个最小值。push()时检测x是否小于等于min_stk 的peek(), 若true,则同时push进min_stk.
pop()时若该值等于min_stk.peek()则同时对min_stk进行pop()操作。
getMin()返回min_stk.peek()即可。
Note: 1. 使用peek(), pop()之前,都要检测stack.empty(), 否则会throw exception.
AC Java:
class MinStack {
private Stack<Integer> stk = new Stack<Integer>();
private Stack<Integer> min_stk = new Stack<Integer>();
public void push(int x) {
stk.push(x);
if(min_stk.empty() || min_stk.peek()>=x){
min_stk.push(x);
}
}
public void pop() {
if(stk.empty()){
return;
}else{
int top = stk.pop();
if(!min_stk.empty() && top==min_stk.peek()){
min_stk.pop();
}
}
}
public int top() {
if(stk.empty()){
return Integer.MAX_VALUE;
}
return stk.peek();
}
public int getMin() {
if(min_stk.empty()){
return Integer.MAX_VALUE;
}
return min_stk.peek();
}
}