1. 实现一个栈,可以在最小时间复杂度内计算出栈中的最小值。空间复杂度无视。
package lime.xiaoniu; import java.util.Iterator; import java.util.Stack; /** * 实现一个栈,可以在最小时间复杂度内计算出栈中的最小值。空间复杂度无视。 */ public class DevilStack { public static void main(String[] args){ DevilStack stack = new DevilStack(); for(int i = 10;i > 0;i--){ stack.push((int)(Math.random() * 100)); } stack.inOrder(); while (!stack.isEmpty()){ System.out.println("mixStackPop : " + stack.peekMixData() + " dataStackPop : " + stack.pop()); } } private Stack<Integer> dataStack = new Stack<Integer>(); private Stack<Integer> mixStack = new Stack<Integer>(); private Integer mixData = Integer.MAX_VALUE; public boolean push(Integer data){ if(null == data){ return false; } dataStack.push(data); mixStack.push(mixData = Math.min(mixData,data)); return true; } public Integer pop(){ if(dataStack.isEmpty()){ return null; } mixStack.pop(); return dataStack.pop(); } public Integer peekMixData(){ if(dataStack.isEmpty()){ return null; } return mixStack.peek(); } public void inOrder(){ if(dataStack.isEmpty()){ return; } Iterator<Integer> iterator = dataStack.iterator(); System.out.print("dataStack : " ); for(;iterator.hasNext();){ System.out.print(iterator.next() + " "); } System.out.print(" mixStack : "); for(iterator = mixStack.iterator();iterator.hasNext();){ System.out.print(iterator.next() + " "); } System.out.println(); } public boolean isEmpty(){ return dataStack.isEmpty(); } }
啦啦啦