java:
class MinStack {
Deque<Integer> stack1;
Deque<Integer> stack2;
public MinStack() {
stack1=new LinkedList<>();
stack2=new LinkedList<>();
}
public void push(int val) {
stack1.offer(val);
if(stack2.isEmpty() || stack2.peekLast()>val){
stack2.offer(val);
}else{
stack2.offer(stack2.peekLast());
}
}
public void pop() {
stack1.pollLast();
stack2.pollLast();
}
public int top() {
return stack1.peekLast();
}
public int getMin() {
return stack2.peekLast();
}
}
python3:
self.stack[-1]取栈顶
math.inf
常量返回浮点正无穷大;对于负无穷大,请使用-math.inf
class MinStack:
def __init__(self):
self.stack = []
self.min_stack = [math.inf]
def push(self, val: int) -> None:
self.stack.append(val)
self.min_stack.append(min(val,self.min_stack[-1]))
def pop(self) -> None:
self.stack.pop()
self.min_stack.pop()
def top(self) -> int:
return self.stack[-1]
def getMin(self) -> int:
return self.min_stack[-1]