forked from super30admin/Design-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmin_stack.py
66 lines (52 loc) · 1.24 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
58
59
60
61
62
63
64
65
66
'''
Time Complexity :
push : O(1)
pop : O(1)
top : O(1)
getMin : O(1)
Space Complexity : O(n)
Did this code successfully run on Leetcode : yes
Any problem you faced while coding this : No
'''
class MinStack(object):
def __init__(self):
self.stack=[]
self.min_stack = []
def push(self, val):
"""
:type val: int
:rtype: None
"""
self.stack.append(val)
if not self.min_stack or val<=self.min_stack[-1]:
self.min_stack.append(val)
def pop(self):
"""
:rtype: None
"""
if not self.stack:
return None
element = self.stack.pop()
if element == self.min_stack[-1]:
self.min_stack.pop()
return element
def top(self):
"""
:rtype: int
"""
if self.stack:
return self.stack[-1]
return None
def getMin(self):
"""
:rtype: int
"""
if self.min_stack:
return self.min_stack[-1]
return None
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()