GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — PythonSampleCodes/Algorithm/StackQueue/Min-Stack.py at master · behappyyoung/PythonSampleCodes Expand file tree/ Copy pathMin-Stack.pyMore file actions 86 lines (66 loc) · 1.86 KB / Copy pathMin-Stack.pyFile metadata and controls86 lines (66 loc) · 1.86 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 """ Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) Push element x onto stack. pop() Removes the element on top of the stack. top() Get the top element. getMin() Retrieve the minimum element in the stack. all the operations have to be constant time operations. Q: What should getMin() do on empty stack? A: In this case, return -1. Q: What should pop do on empty stack? A: In this case, nothing. Q: What should top() do on empty stack? A: In this case, return -1 """ class MinStack: def __init__(self): """ initialize your data structure here. """ self.stack = [] self.minNum = [] def push(self, x: int) -> None: self.stack.append(x) if self.minNum: if x <= self.minNum[-1]: # x is smaller than current minNum self.minNum.append(x) else: self.minNum.append(x) def pop(self) -> None: if self.stack: if self.stack[-1] == self.minNum[-1]: self.minNum = self.minNum[:-1] self.stack = self.stack[:-1] else: self.stack.pop() def top(self) -> int: if self.stack: return self.stack[-1] return -1 def getMin(self) -> int: if self.minNum: return self.minNum[-1] return -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() minstack = MinStack() minstack.pop() minstack.push(10) minstack.push(9) print(minstack.getMin()) minstack.push(8) print(minstack.getMin()) minstack.push(7) print(minstack.getMin()) minstack.push(6) print(minstack.getMin()) minstack.pop() print(minstack.getMin()) print(minstack.stack) print(minstack.getMin()) minstack.pop() print(minstack.stack) |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |