Min Stack (E)
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.
Example:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> Returns -3.
minStack.pop();
minStack.top(); --> Returns 0.
minStack.getMin(); --> Returns -2.
题意
设计一个栈结构,在实现栈的基础功能之外,还需要实现一个获取当前栈最小值的方法,每个操作的时间复杂度要求为O(1)O(1)O(1)。
思路
维护两个栈来实现输出最小值:一个为普通栈stack,一个用于保存与当前普通栈中元素相对应的最小值栈minStack。push新元素x时,如果当前minStack为空,或者x值小于等于minStack栈顶元素,说明x是加入后普通栈中的最小值,需要在minStack入栈;pop栈顶元素x时,如果x与minStack栈顶元素相同,说明x正是当前普通栈中的最小值,也需要在minStack出栈。
代码实现
class MinStack {
private LinkedList<Integer> stack;
private LinkedList<Integer> minStack;
/** initialize your data structure here. */
public MinStack() {
stack = new LinkedList<>();
minStack = new LinkedList<>();
}
public void push(int x) {
// 注意要使用<=,不然会引发NullPointerException
if (minStack.isEmpty() || x <= minStack.peek()) {
minStack.push(x);
}
stack.push(x);
}
public void pop() {
int min = minStack.peek();
if (stack.peek() == min) {
minStack.pop();
}
stack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return minStack.peek();
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
本文介绍了一种特殊的数据结构MinStack的设计与实现方法,该结构能在常数时间内完成压栈、弹栈、获取栈顶元素及获取当前栈中最小元素的操作。通过维护两个栈,即普通栈和最小值栈,实现了所有操作的高效执行。
1144

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



