要求:
1. 定义栈的数据结构,要求添加一个 min函数,能够得到栈的最小元素
2. 要求函数 min、push 以及 pop 的时间复杂度都是 O(1)
思路: 构建一个辅助栈, 只有当前入栈的数据小于该辅助栈的栈顶元素时,才将其push到辅助栈, 保证辅助栈的栈顶元素总为最小,当出栈时,如果出栈元素大于辅助栈栈顶元素,则该元素必然不在辅助栈中,因为辅助栈保留了原始栈的入栈顺序(只按大到小存储 舍弃了一些元素), 该较大元素在入栈时就已经被辅助栈过滤掉了,如果出栈元素小于或等于辅助栈栈顶元素,则辅助栈也进行pop操作
1packagecom.rui.microsoft;23importjava.util.Stack;45publicclassTest02_MinStack {67publicstaticvoidmain(String[] args) {8MyStack myStack =newMyStack();9myStack.push(5);10myStack.push(3);11myStack.push(1);12myStack.push(6);1314System.out.PRintln(myStack.min());1516myStack.pop();17System.out.println(myStack.min());1819myStack.pop();20System.out.println(myStack.min());2122}2324staticclassMyStack{25privateStack<Integer> stack =newStack<Integer>();26privateStack<Integer> minStack =newStack<Integer>();2728publicvoidpush(inti){29stack.push(i);3031if(minStack.isEmpty()){32minStack.push(i);33}else{34intmin =minStack.peek();35//minStack only push item smaller than its top item36//minStack只入栈比其栈顶元素小的元素37if(i <min){38minStack.push(i);39}40}41}4243publicInteger pop(){44Integer i =stack.pop();45//when pop an item from original stack46//we need to process the minStack also47//if the item popped from original stack is larger than minStack's top item48//it means this item should not exist in minStack49if(i <=minStack.peek()){50minStack.pop();51}52returni;53}5455publicInteger min(){56returnminStack.peek();57}58}59}