-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtest.py
80 lines (65 loc) · 1.65 KB
/
test.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
class MinStack(object):
def __init__(self):
"""
data structure .
"""
self.stack = []
self.minimum = None
def push(self, x):
"""
:type x: int
:rtype: None
"""
if len(self.stack) == 0:
self.stack.append(x)
self.minimum = x
else:
if x >= self.minimum:
self.stack.append(x)
else:
self.stack.append(2*x - self.minimum)
self.minimum = x
def pop(self):
"""
:rtype: None
"""
if len(self.stack) == 0:
raise IndexError
if self.stack[-1] < self.minimum: # Using this as flag for setting next minimum
val = self.minimum
self.minimum = 2*self.minimum - self.stack[-1]
self.stack.pop()
return val
return self.stack.pop()
def top(self):
"""
:rtype: int
"""
if len(self.stack) == 0:
raise IndexError
if self.stack[-1] < self.minimum:
if self.stack[-1] < 0:
return self.minimum
else:
return 2*self.minimum - self.stack[-1]
return self.stack[-1]
def getMin(self):
"""
:rtype: int
"""
if len(self.stack) == 0:
return -1
return self.minimum
'''
push:O(1)
getMin:O(1)
pop:O(1)
'''
heap=MinStack()
heap.push(1)
heap.push(2)
heap.push(10)
heap.push(-10)
print("min ->"+str(heap.getMin()))
print("poped ->"+str(heap.pop()))
print("min ->" + str(heap.getMin()))