题目描述:
设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈
push(x) – 将元素 x 推入栈中
pop() – 删除栈顶的元素
top() – 获取栈顶元素
getMin() – 检索栈中的最小元素
示例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.
/**
* 方法:通过构建两个栈来实现最小栈
* 思路:stack 里放元素,minStack 里栈顶放当前元素中的最小值
*/
class MinStack {
Stack<Integer> stack;
Stack<Integer> minStack;
/** initialize your data structure here. */
public MinStack() {
stack = new Stack<>();
minStack = new Stack<>();
}
public void push(int x) {
stack.push(x);
if (!minStack.isEmpty()) {
int top = minStack.peek();
//小于的时候才入栈
if (x <= top) {
minStack.push(x);
}
}else{
minStack.push(x);
}
}
public void pop() {
//如果 stack 中栈顶元素 == minStack 栈顶元素,
//出栈的时候 minStack 的栈顶元素也需要出,虽然该元素是 minStack 中最小值,
//但这个元素已经不存在了
int pop = stack.pop();
int top = minStack.peek();
if (pop == top) {
minStack.pop();
}
}
public int top() {
return stack.peek();
}
public int getMin() {
return minStack.peek();
}
}