## Solutions ### first try ```python class MinStack(object): def __init__(self): self.stack = [] def push(self, val): """ :type val: int :rtype: None """ self.stack.append(val) def pop(self): """ :rtype: None """ self.stack.pop() def top(self): """ :rtype: int """ return self.stack[-1] def getMin(self): """ :rtype: int """ min = self.top() for element in self.stack: if element < min: min = element return min # Your MinStack object will be instantiated and called as such: # obj = MinStack() # obj.push(val) # obj.pop() # param_3 = obj.top() # param_4 = obj.getMin() ``` - Complexity Analysis - Time complexity is On because we use for loop in getMin - Space complexity is ### 优化 getMin ```python class MinStack(object): def __init__(self): self.stack = [] self.min_stack = [] def push(self, val): """ :type val: int :rtype: None """ self.stack.append(val) if not self.min_stack or val < self.min_stack[-1]: self.min_stack.append(val) else: self.min_stack.append(self.min_stack[-1]) def pop(self): """ :rtype: None """ self.stack.pop() self.min_stack.pop() def top(self): """ :rtype: int """ return self.stack[-1] def getMin(self): """ :rtype: int """ if self.min_stack: return self.min_stack[-1] # Your MinStack object will be instantiated and called as such: # obj = MinStack() # obj.push(val) # obj.pop() # param_3 = obj.top() # param_4 = obj.getMin() ``` core idea: maintain a synchronized `min_stack`, push the smallest value inside each operation, so we can get the min value directly