标签:leetcode app object __init__ [] elf 操作 今天 init
问题描述:
设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
示例:
MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); --> 返回 -3. minStack.pop(); minStack.top(); --> 返回 0. minStack.getMin(); --> 返回 -2.
方法1:
1 class MinStack(object): 2 3 def __init__(self): 4 """ 5 initialize your data structure here. 6 """ 7 self.m=[] 8 9 def push(self, x): 10 """ 11 :type x: int 12 :rtype: void 13 """ 14 self.m.append(x) 15 16 17 def pop(self): 18 """ 19 :rtype: void 20 """ 21 if len(self.m) > 0: 22 temp = self.m[-1] 23 self.m=self.m[::-1] 24 self.m.remove(temp) 25 self.m=self.m[::-1] 26 return temp 27 else: 28 return 29 30 def top(self): 31 """ 32 :rtype: int 33 """ 34 if len(self.m) > 0: 35 return self.m[-1] 36 else: 37 return 38 def getMin(self): 39 """ 40 :rtype: int 41 """ 42 return min(self.m)
官方:
1 class MinStack(object): 2 3 def __init__(self): 4 """ 5 initialize your data structure here. 6 """ 7 self.stack=[] 8 self.stack_bk=[] 9 10 11 def push(self, x): 12 """ 13 :type x: int 14 :rtype: void 15 """ 16 if self.stack==[]: 17 self.stack_bk.append(x) 18 else: 19 if x<=self.stack_bk[-1]: 20 self.stack_bk.append(x) 21 self.stack.append(x) 22 23 def pop(self): 24 """ 25 :rtype: void 26 """ 27 if self.stack[-1]==self.stack_bk[-1]: 28 self.stack_bk.pop() 29 self.stack.pop() 30 31 def top(self): 32 """ 33 :rtype: int 34 """ 35 return self.stack[-1] 36 37 def getMin(self): 38 """ 39 :rtype: int 40 """ 41 return self.stack_bk[-1]
今天课太多了,明天补回来吧。。。。
2018-09-13 23:05:48
标签:leetcode app object __init__ [] elf 操作 今天 init
原文地址:https://www.cnblogs.com/NPC-assange/p/9643845.html