小知识,大挑战!本文正在参与“程序员必备小知识”创作活动
题目描述
设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
- push(x) —— 将元素 x 推入栈中。
- pop() —— 删除栈顶的元素。
- top() —— 获取栈顶元素。
- getMin() —— 检索栈中的最小元素。
示例:
输入:
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
输出:
[null,null,null,null,-3,null,0,-2]
解释:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
提示:
pop、top 和 getMin 操作总是在 非空栈 上调用。
题解
1.双栈
1.使用两个栈,一个正常进行压栈弹出.另一个栈存储最小值.
2.当压栈时,与最小值栈比较是否为最小值,如果是就同时压入最小值栈
3.弹出时,判断与最小栈的栈顶大小是否相等,如果相等,就一起弹出
4.最小值栈的栈顶存储的就是当前的最小值
class MyQueue {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
public MyQueue() {
stack1 = new Stack<Integer>();
stack2 = new Stack<Integer>();
}
public void push(int x) {
stack1.push(x);
// 这里的statck2不能动,只有在pop的时候才能调用,否则不就是栈2在存储吗?
// stack2.push(stack1.pop());
}
// 判断stack2是否为空,输出stack栈顶.如果为空,那么将stack1中的所有元素压入stack2,保证元素顺序完整
public int pop() {
if (!stack2.isEmpty()) {
return stack2.pop();
}
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
return stack2.pop();
}
// 与pop的步骤相同
public int peek() {
if (!stack2.isEmpty()) {
return stack2.peek();
}
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
return stack2.peek();
}
public boolean empty() {
if (stack1.isEmpty() && stack2.isEmpty()) {
return true;
}
return false;
}
}