Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- getMin() -- Retrieve the minimum element in the stack.
class MinStack {
private Stack<Integer> stackData = new Stack<Integer>();
private Stack<Integer> stackMin = new Stack<Integer>();
public void push(int x) {
if (stackMin.isEmpty()) {
stackMin.push(x);
} else if (x <= getMin()) {
stackMin.push(x);
}
stackData.push(x);
}
public void pop() {
if (stackData.isEmpty()) {
return;
}
Integer pop = stackData.pop();
if (pop == getMin()) {
stackMin.pop();
}
}
public int top() {
return stackData.peek();
}
public int getMin() {
if (stackMin.isEmpty()) {
return 0;
}
return stackMin.peek();
}
}
本文介绍了一个特殊的数据结构——最小值栈,它能在常数时间内完成压栈、弹栈、获取栈顶元素及获取当前栈中最小元素的操作。通过维护两个栈:一个用于存放实际数据,另一个用于跟踪历史最小值,从而实现了高效的最小值检索。
1501

被折叠的 条评论
为什么被折叠?



