FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
LeetCode-Solutions/Python/max-stack.py at master · Monika-R/LeetCode-Solutions · GitHub
Monika-R
/
LeetCode-Solutions
Public
forked from
kamyu104/LeetCode-Solutions
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
LeetCode-Solutions
/
Python
/
max-stack.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
79 lines (60 loc) · 1.78 KB
Breadcrumbs
LeetCode-Solutions
/
Python
/
max-stack.py
Copy path
File metadata and controls
79 lines (60 loc) · 1.78 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
# Time: push: O(1)
# pop: O(n), there is no built-in SortedDict in python. If applied, it could be reduced to O(logn)
# popMax: O(n)
# top: O(1)
# peekMax: O(1)
# Space: O(n), n is the number of values in the current stack
import
collections
class
MaxStack
(
object
):
def
__init__
(
self
):
"""
initialize your data structure here.
"""
self
.
__idx_to_val
=
collections
.
defaultdict
(
int
)
self
.
__val_to_idxs
=
collections
.
defaultdict
(
list
)
self
.
__top
=
None
self
.
__max
=
None
def
push
(
self
,
x
):
"""
:type x: int
:rtype: void
"""
idx
=
self
.
__val_to_idxs
[
self
.
__top
][
-
1
]
+
1
if
self
.
__val_to_idxs
else
0
self
.
__idx_to_val
[
idx
]
=
x
self
.
__val_to_idxs
[
x
].
append
(
idx
)
self
.
__top
=
x
self
.
__max
=
max
(
self
.
__max
,
x
)
def
pop
(
self
):
"""
:rtype: int
"""
val
=
self
.
__top
self
.
__remove
(
val
)
return
val
def
top
(
self
):
"""
:rtype: int
"""
return
self
.
__top
def
peekMax
(
self
):
"""
:rtype: int
"""
return
self
.
__max
def
popMax
(
self
):
"""
:rtype: int
"""
val
=
self
.
__max
self
.
__remove
(
val
)
return
val
def
__remove
(
self
,
val
):
idx
=
self
.
__val_to_idxs
[
val
][
-
1
]
self
.
__val_to_idxs
[
val
].
pop
()
if
not
self
.
__val_to_idxs
[
val
]:
del
self
.
__val_to_idxs
[
val
]
del
self
.
__idx_to_val
[
idx
]
if
val
==
self
.
__top
:
self
.
__top
=
self
.
__idx_to_val
[
max
(
self
.
__idx_to_val
.
keys
())]
if
self
.
__idx_to_val
else
None
if
val
==
self
.
__max
:
self
.
__max
=
max
(
self
.
__val_to_idxs
.
keys
())
if
self
.
__val_to_idxs
else
None
Back
|
FazBrowse Home
|
New Git URL