考察点
双栈
知识点
题目
分析
题目需要一个能够得到栈的最小元素的min函数,并且min函数,pop,push都要求是O(1)的时间复杂度。遇到栈思维要往双栈上考虑,这种情况一个栈肯定完成不了,需要一个辅助栈,既然要求 O(1)时间内拿到最小元素,那么这个辅助栈的栈顶存的肯定是当前所有元素中最小的元素,所以只要每次入栈的时候取当前元素和辅助栈顶层数据最小值入栈即可。切记注意辅助栈需要和数据栈一起增长,这样当数据栈弹出的时候辅助栈的栈顶数据依然是所有元素中最小的元素
import java.util.Deque;
import java.util.LinkedList;public class Stack {private Deque stack;private Deque minStack;public Stack() {stack = new LinkedList<>();minStack = new LinkedList<>();}public void push(int val) {stack.push(val);if (minStack.peek() == null){minStack.push(val);return;}int peekData = (int) minStack.peek();if (peekData > val) {minStack.push(val);} else {minStack.push(peekData);}}public void pop() {if (minStack.peek() == null) {throw new Error("stack empty");}minStack.pop();stack.pop();}public int min() {if (minStack.peek() == null) {throw new Error("stack empty");}int peekData = (int) minStack.peek();return peekData;}
}
public class TwentyOne {public static void main(String[] args) {Stack stack = new Stack();stack.push(3);System.out.println(stack.min());stack.push(4);System.out.println(stack.min());stack.push(2);System.out.println(stack.min());stack.push(1);System.out.println(stack.min());stack.pop();System.out.println(stack.min());stack.pop();System.out.println(stack.min());stack.push(0);System.out.println(stack.min());}
}