学而不思则罔,思而不学则殆
题目
设计一个栈,使它可以在O(1)的时间复杂度实现push,pop和min操作。所谓min操作就是获取栈内最小元素
思路
空间换时间
- 使用双栈,一个主栈,保存主元素;一个最小元素栈,保存当前栈内的最小元素
- 入栈的时候,如果新加入的元素比最小元素栈内的栈顶元素小就两个栈都加入,否则就加入主元素栈
- 出栈的时候,如果当前元素等于最小元素栈栈顶的元素,那么最小元素栈也出栈
代码
class MinStack {
Stack<Integer> valueStack = new Stack<>();//主元素栈
Stack<Integer> minStack = new Stack<>();//最小元素栈
void push(int value) {
valueStack.push(value);
//更新最小栈
if (minStack.size() == 0) {
minStack.push(value);
} else {
//新加入的元素<=最小栈栈顶元素,入栈
if (minStack.peek() >= value) {
minStack.push(value);
}
}
}
int pop() {
if (valueStack.size() == 0) {
return Integer.MAX_VALUE;
} else {
Integer value = valueStack.pop();
//更新最小栈,出栈
if (minStack.peek().equals(value)) {
minStack.pop();
}
return value;
}
}
int min() {
if (minStack.size() == 0) {
return Integer.MAX_VALUE;
} else {
return minStack.peek();
}
}
void show() {
System.out.println("valueStack:" + valueStack);
System.out.println("minStack:" + minStack);
}
}
测试
测试
MinStack minStack = new MinStack();
minStack.push(10);
minStack.push(9);
minStack.push(9);
minStack.push(8);
minStack.push(15);
minStack.push(5);
minStack.show();
//valueStack:[10, 9, 9, 8, 15, 5]
//minStack:[10, 9, 9, 8, 5]
System.out.println(minStack.min()); //5
System.out.println(minStack.pop()); //5
minStack.show();
//valueStack:[10, 9, 9, 8, 15]
//minStack:[10, 9, 9, 8]
System.out.println(minStack.min()); //8
System.out.println(minStack.pop()); //15
System.out.println(minStack.pop()); //8
minStack.show();
//valueStack:[10, 9, 9]
//minStack:[10, 9, 9]
System.out.println(minStack.min());//9
System.out.println(minStack.pop());//9
minStack.show();
//valueStack:[10, 9]
//minStack:[10, 9]
测试二
private static void test2() {
MinStack minStack = new MinStack();
Random random = new Random();
for (int i = 0; i < 20; i++) {
minStack.push(random.nextInt(100));
}
minStack.show();
}
valueStack:[29, 9, 53, 79, 96, 7, 51, 51, 45, 78, 56, 61, 36, 24, 41, 9, 28, 78, 64, 26]
minStack:[29, 9, 7]