Solution 1
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.array = []
def push(self, x: int) -> None:
cur_min = self.getMin()
if cur_min == None or x < cur_min: cur_min = x #here we can not use if not cur_min. Because if cur_min is 0, it will be considered as not cur_min is true!
self.array.append((x, cur_min))
def pop(self) -> None:
self.array.pop()
def top(self) -> int:
if not self.array: return None
return self.array[-1][0]
def getMin(self) -> int:
if not self.array: return None
return self.array[-1][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.getMin()
Time complexity and space complexity are O(1).
Warning: Do not use ” if not x”, if “x” is a number!