Question: design a stack which, in addition to
push and pop, also has a function min which returns the
minimum element? Push, pop and min should
push and pop, also has a function min which returns the
minimum element? Push, pop and min should
all operate in O(1) time.
Idea: Use two stacks: stack and minStack
stack: insert data as usual
minStack: always keep minimum element on the top of minStack
class minStack{
Stack<Integer> stack=new Stack<Integer>();
Stack<Integer> minStack=new Stack<Integer>();
public void push(int data){
stack.add(data);
if(data<min()){
minStack.add(data);
}
}
public int pop(){
int temp=stack.pop();
if(temp==min()){
minStack.pop();
}
return temp;
}
public int min(){
if(!minStack.isEmpty()) {
return minStack.peek();
}else {
return Integer.MAX_VALUE;
}
}
}
本文介绍了一种利用两个栈实现的最小元素栈设计,其中push、pop和min操作均可在O(1)时间内完成。通过在min栈中始终保持最小元素,该方案有效地解决了最小元素的快速查询问题。

477

被折叠的 条评论
为什么被折叠?



