java栈,获取最小值GetMin方法。要求时间复杂度为O(1)
import java.util.Stack;
public class MINSTACK {
private Stack<Integer> mainStark=new Stack<Integer>();
private Stack<Integer> minStark=new Stack<Integer>();
/**
* 入栈元素
* @param element
*/
public void push(int element){
mainStark.push(element);
/**如果minStark为空或者当element值小于Minstark栈顶的值
*minStark也入栈当前元素
*/
if (minStark.empty()||element<=minStark.peek()){
minStark.push(element);
}
}
/**
* 出栈操作
* @return
*/
public Integer pop(){
//查看两个栈的栈顶,如果最小栈与主栈相同。则最小栈同时出栈
if (mainStark.peek().equals(minStark.peek())){
minStark.pop();
}
return mainStark.pop();
}
public int getMin()throws Exception{
if (mainStark.empty()){
throw new Exception("Stack is empty");
}
return minStark.peek();
}
public static void main(String[] args) throws Exception {
MINSTACK stack =new MINSTACK();stack.push(4);
stack.push(4);
stack.push(9);
stack.push(7);
stack.push(3);
stack.push(8);
stack.push(5);
System.out.println(stack.getMin());
stack.pop();
stack.pop();
stack.pop();
stack.pop();
System.out.println(stack.getMin());
}
}
时间复杂度为O(1),空间复杂度最坏情况下为O(n)