【LeeCode】155. 最小栈(赋予栈获得所有数最小值的功能)
设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) – 将元素 x 推入栈中。
pop() – 删除栈顶的元素。
top() – 获取栈顶元素。
getMin() – 检索栈中的最小元素。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/min-stack
建立一个数据栈,一个辅助栈(记录数据的最小值):
建立两个Stack成员变量,一个储存栈的基本数据,一个储存最小值。
push进来一个元素,如果此元素小于等于minStack最上面的元素,将其压入minStack
pop走一个元素,如果此元素等于minStack最上面的元素,将minStack最上面的元素弹走
显然现存最小的元素可以从minStack最顶上得到。
class MinStack {
private Stack<Integer> stack;
private Stack<Integer> minStack;
public MinStack() {
stack = new Stack();
minStack = new Stack();
}
public void push(int x) {
stack.push(x);
if (minStack.empty() || x <= minStack.peek()) {
minStack.push(x);
}
}
public void pop() {
int tmp = stack.pop();
if (minStack.peek() == tmp) {
minStack.pop();
}
}
public int top() {
return stack.peek();
}
public int getMin() {
return minStack.peek();
}
}