设计一个支持 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.
因为要在O(1)时间复杂度完成查找最小元素,因此需要另一个容器来存储当前最小元素,并随着栈的入栈出栈动态更新。
Java
class MinStack {
//存储数据
private Stack<Integer> dataStack;
//存储最小值
private Stack<Integer> minStack;
/** initialize your data structure here. */
public MinStack() {
dataStack = new Stack<Integer>();
minStack = new Stack<Integer>();
}
public void push(int x) {
dataStack.push(x);
if(minStack.isEmpty() || minStack.peek()>=x)
minStack.push(x);
}
public void pop() {
int top = dataStack.pop();
if(minStack.peek() == top){
minStack.pop();
}
}
public int top() {
return dataStack.peek();
}
public int getMin() {
return minStack.peek();
}
}
Python
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.data = []
self.min = []
def push(self, x: int) -> None:
self.data.append(x)
if len(self.min) == 0 or x <= self.min[-1]:
self.min.append(x)
def pop(self) -> None:
top = self.data.pop()
if top == self.min[-1]:
self.min.pop()
def top(self) -> int:
return self.data[-1]
def getMin(self) -> int:
return self.min[-1]
因篇幅问题不能全部显示,请点此查看更多更全内容