题目
设计一个支持 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.
思路
设计题,主要体现在代码的规范性上,在面试的时候,这题的思路可以利用两个栈来实现,一个栈存取进入的数值,另外一个辅助栈存贮当前最小的数值,就可以实现getMIn
方法时间复杂度为O(1)
了,代码如下:
class MinStack {
Stack<Integer> mainStack;
Stack<Integer> helpStack;
/** initialize your data structure here. */
public MinStack() {
mainStack=new Stack<>();
helpStack=new Stack<>();
}
public void push(int x) {
if (mainStack.isEmpty() || x <= getMin()){
helpStack.push(x);
}
mainStack.push(x);
}
public void pop() {
if (mainStack.isEmpty()){
throw new RuntimeException("stack is null!");
}
if (mainStack.peek() == getMin()){
helpStack.pop();
}
mainStack.pop();
}
public int top() {
if (mainStack.isEmpty()){
throw new RuntimeException("stack is null!");
}
return mainStack.peek();
}
public int getMin() {
if (helpStack.isEmpty()){
throw new RuntimeException("stack is null!");
}
return helpStack.peek();
}
}