题目
请设计一个栈,除了常规栈支持的pop与push函数以外,还支持min函数,该函数返回栈元素中的最小值。执行push、pop和min操作的时间复杂度必须为O(1)。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
思路
1.使用两个系统提供的栈stack1,stack2
2.push操作时向statck1中压入元素i,如果statck2的栈顶元素大于i,将i压入stack2否则将stack2的栈顶元素压入stack2
3.pop操作时将stack1与stack2中的元素同时弹出
4.getMin操作查看stack2的栈顶元素
图解

代码实现
public class SpecialStack {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int x) {
stack1.push(x);
if (stack2.isEmpty() || stack2.peek() > x) {
stack2.push(x);
} else {
stack2.push(stack2.peek());
}
}
public int pop() {
if (!stack1.isEmpty() && !stack2.isEmpty()) {
stack2.pop();
return stack1.pop();
} else {
throw new RuntimeException("栈为空");
}
}
public int top() {
if (!stack1.isEmpty()) {
return stack1.peek();
}
throw new RuntimeException("栈为空");
}
public int getMin() {
if (!stack1.isEmpty()) {
return stack2.peek();
}
throw new RuntimeException("栈为空");
}
}