mycode 21.48%
class MinStack(object): def __init__(self): """ initialize your data structure here. """ self.res = [] def push(self, x): """ :type x: int :rtype: None """ self.res.append(x) def pop(self): """ :rtype: None """ if not self.res: return None else: val = self.res[-1] self.res[:] = self.res[:-1] return val def top(self): """ :rtype: int """ if not self.res: return None else: return self.res[-1] def getMin(self): """ :rtype: int """ if not self.res: return None else: return min(self.res) # 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()
列表是有pop操作的
self.res.pop()
参考
始终更新最小值,所以节省 了时间
class MinStack(object): def __init__(self): """ initialize your data structure here. """ self.stack = [] self.minval = 99999999999999999 def push(self, x): """ :type x: int :rtype: None """ if(x < self.minval): self.minval = x self.stack.append(x) def pop(self): """ :rtype: None """ if(self.stack[-1] == self.minval): self.minval = 99999999999 for num in self.stack[0:-1]: if(num < self.minval): self.minval = num self.stack.pop(-1) def top(self): """ :rtype: int """ return self.stack[-1] def getMin(self): """ :rtype: int """ return self.minval # 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()