GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — PythonSampleCodes/Algorithm/StackQueue/Min-Stack.py at master · behappyyoung/PythonSampleCodes

Expand file tree

/

Min-Stack.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
86 lines (66 loc) · 1.86 KB
/

Min-Stack.py

Copy path

File metadata and controls

86 lines (66 loc) · 1.86 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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.