问题描述:
设计一个堆栈,支持除普通堆栈功能之外,查找最大值和移除最大值的功能
思路:
双堆栈,之前题目中遇到过。一个堆栈负责正常来往顺序,另外一个堆栈保持与第一个堆栈等高,且对应高度的值代表在这个高度上的最大值
代码如下:
class MaxStack {
Stack<Integer> normalStack;
Stack<Integer> maxStack;
/** initialize your data structure here. */
public MaxStack() {
normalStack=new Stack<Integer>();
maxStack=new Stack<Integer>();
}
public void push(int x) {
normalStack.push(x);
if(maxStack.isEmpty()) maxStack.push(x);
else{
int max=maxStack.peek();
if(x<max) maxStack.push(max);
else maxStack.push(x);
}
}
public int pop() {
maxStack.pop();
return normalStack.pop();
}
public int top() {
return normalStack.peek();
}
public int peekMax() {
return maxStack.peek();
}
public int popMax() {
int max=maxStack.peek();
Stack<Integer> temp=new Stack<>();
while(normalStack.peek()!=max){
temp.push(pop());
}
pop();
while(!temp.isEmpty()){
push(temp.pop());
}
return max;
}
}
时间复杂度: 除popMax()之外都是O(1), popMax()是O(n)