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;
}
}
}