设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
- push(x) -- 将元素 x 推入栈中。
- pop() -- 删除栈顶的元素。
- top() -- 获取栈顶元素。
- getMin() -- 检索栈中的最小元素。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
思路:
使用一个辅助栈stackMin来保存栈中的最小元素。stackMin始终记录着stackData中的最小值,所以stackMin的栈顶元素始终是当前stackData中的最小值。
代码:
class MinStack {
private Stack<Integer> stackData;
private Stack<Integer> stackMin;
/** 构造方法 */
public MinStack() {
stackData = new Stack<Integer>();
stackMin = new Stack<Integer>();
}
/*将元素x推入栈中*/
public void push(int x) {
if(stackMin.empty()) {
stackMin.push(x);
} else if(x <= getMin()) {
stackMin.push(x);
} else {
int newMin = getMin();
stackMin.push(newMin);
}
stackData.push(x);
}
/*删除栈顶元素*/
public void pop() {
if(stackData.empty()) {
throw new RuntimeException("your stack is empty!");
}
stackMin.pop();
stackData.pop();
}
/*获取栈顶元素*/
public int top() {
if(stackData.empty()) {
throw new RuntimeException("your stack is empty!");
}
return stackData.peek();
}
/*检索栈中的最小元素*/
public int getMin() {
if(stackMin.empty()) {
throw new RuntimeException("your stack is empty!");
}
return stackMin.peek();
}
}
测评结果:


本文介绍了一种名为MinStack的数据结构,它支持push、pop、top和getMin操作,且getMin操作可在常数时间内完成。通过使用辅助栈stackMin记录最小值,确保了即使在频繁操作下也能快速获取栈中最小元素。
3046

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



