-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmin_stack.py
More file actions
59 lines (51 loc) · 1.28 KB
/
min_stack.py
File metadata and controls
59 lines (51 loc) · 1.28 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
# 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.
# get_min() -- Retrieve the minimum element in the stack.
"""
>>> minStack = MinStack()
>>> minStack.push(2147483646)
>>> minStack.push(2147483646)
>>> minStack.push(2147483647)
>>> minStack.top()
2147483647
>>> minStack.pop()
>>> minStack.get_min()
2147483646
>>> minStack.pop()
>>> minStack.get_min()
2147483646
>>> minStack.pop()
>>> minStack.push(2147483647)
>>> minStack.top()
2147483647
>>> minStack.get_min()
2147483647
>>> minStack.push(-2147483648)
>>> minStack.top()
-2147483648
>>> minStack.get_min()
-2147483648
>>> minStack.pop()
>>> minStack.get_min()
2147483647
"""
import math
class MinStack:
def __init__(self):
self.queue = []
self.min_value = [math.inf]
def push(self, x: int) -> None:
self.queue.append(x)
self.min_value.append(min(self.min_value[-1], x))
def pop(self) -> None:
if self.queue:
self.queue.pop()
self.min_value.pop()
def top(self) -> int:
if self.queue:
return self.queue[-1]
def get_min(self) -> int:
return self.min_value[-1]