「剣指Offer(第二版)」面接問題30.min関数を含むスタック
1279 ワード
, min , min、push pop O(1)。
:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.min(); --> -3.
minStack.pop();
minStack.top(); --> 0.
minStack.min(); --> -2.
:
20000
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.min_stack = []
def push(self, x: int) -> None:
self.stack.append(x)
if len(self.min_stack) == 0:
self.min_stack.append(x)
else:
if x <= self.min_stack[-1]:
self.min_stack.append(x)
def pop(self) -> None:
num = self.stack.pop()
if num == self.min_stack[-1]:
_ = self.min_stack.pop()
def top(self) -> int:
return self.stack[-1]
def min(self) -> int:
if len(self.min_stack) == 0:
return []
else:
return self.min_stack[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.min()