-
Notifications
You must be signed in to change notification settings - Fork 0
/
LC0229.py
39 lines (29 loc) · 961 Bytes
/
LC0229.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
class RandomizedSet:
def __init__(self):
self.stack = []
self.dict = {}
def insert(self, val: int) -> bool:
# dictionary is on average O(1) where as
# checking the array is on average O(n)
if val in self.dict:
return False
self.dict[val] = len(self.stack)
self.stack.append(val)
return True
def remove(self, val: int) -> bool:
# dictionary is on average O(1) where as
# checking the array is on average O(n)
if val not in self.dict:
return False
last = self.stack[-1]
ind = self.dict[val]
self.dict[last] = ind
self.stack[ind] = last
self.stack.pop()
self.dict.pop(val)
return True
def getRandom(self) -> int:
return random.choice(self.stack)
```
feel free to ask Q...
#happytohelpu