题目
设计一个支持push、pop、top操作,并能在常数内检索到最小元素的栈。
分析
使用辅助栈。
当新来的数字小于或等于辅助栈栈顶元素、或者辅助栈为空时,将元素放入。
pop时候,如果原栈出元素,辅助栈有这个元素也要一起出栈。
获得的最小元素就是辅助栈的栈顶。
代码
public class solution155 {
private Stack<Integer> data;
private Stack<Integer> help;
public solution155() {
data = new Stack<>();
help = new Stack<>();
}
public void push(int x){
data.push(x);
if(help.isEmpty()||x<=help.peek())
help.push(x);
}
//要删除,两个栈都得删
public void pop(){
if(!data.isEmpty()){
int top = data.pop();
if(top==help.peek()){
help.pop();
}
}
}
public int top(){
return data.peek();
}
public int getMin(){
return help.peek();
}