-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmin_stack.py
57 lines (46 loc) · 1.17 KB
/
min_stack.py
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
class MinStack:
"""
Implement a stack that supports push, pop, top and getMin in O(1) time.
"""
def __init__(self):
self.elements = []
def push(self, x):
"O(1)"
if len(self.elements) == 0:
self.elements.append((x, x))
else:
self.elements.append((x, min(x, self.getMin())))
def pop(self):
"O(1)"
if len(self.elements) > 0:
return self.elements.pop()[0]
def top(self):
"O(1)"
if len(self.elements) > 0:
return self.elements[-1][0]
else:
return -1
def getMin(self):
"O(1)"
if len(self.elements) > 0:
return self.elements[-1][1]
else:
return -1
def test_min_stack():
stack = MinStack()
stack.pop()
assert stack.top() == -1
assert stack.getMin() == -1
stack.push(10)
stack.push(3)
assert stack.getMin() == 3
stack.pop()
assert stack.getMin() == 10
stack.push(5)
assert stack.getMin() == 5
stack.push(6)
assert stack.getMin() == 5
stack.push(3)
assert stack.getMin() == 3
stack.pop()
assert stack.getMin() == 5