getMin 使用一个栈
import java.util.Stack;
class getMin{
Stack<Integer> stack;
int min;
public getMin(){
stack = new Stack<Integer>();
min = Integer.MIN_VALUE;
}
public void push(int val){
if(stack.isEmpty()){
stack.push(0);
min = val;
}
else{
int diff = val - min;
stack.append(diff);
min = diff>0?min:val;
}
}
public int pop(){
if(stack.isEmpty()) return -1;
int diff = stack.pop();
if(diff < 0){
top = min;
min = top - diff;
}
else{
top = min + diff;
}
return top;
}
public int top(){
if(stack.peek() < 0){
return min;
}
else{
return stack.peek() + min;
}
}
public int get_min(){
if(stack.isEmpty()) return -1;
return min;
}
}
Saying Less Doing More