-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0380-insert-delete-getrandom-o1.py
More file actions
41 lines (32 loc) · 958 Bytes
/
0380-insert-delete-getrandom-o1.py
File metadata and controls
41 lines (32 loc) · 958 Bytes
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
# time complexity: O(1)
# space complexity: O(n)
from random import choice
class RandomizedSet:
def __init__(self):
self.dict = {}
self.list = []
def insert(self, val: int) -> bool:
if val in self.dict:
return False
self.dict[val] = len(self.list)
self.list.append(val)
return True
def remove(self, val: int) -> bool:
if val in self.dict:
lastEle, idx = self.list[-1], self.dict[val]
self.list[idx], self.dict[lastEle] = lastEle, idx
self.list.pop()
del self.dict[val]
return True
return False
def getRandom(self) -> int:
return choice(self.list)
# Your RandomizedSet object will be instantiated and called as such:
obj = RandomizedSet()
print(obj.insert(1))
print(obj.remove(2))
print(obj.insert(2))
print(obj.getRandom())
print(obj.remove(1))
print(obj.insert(2))
print(obj.getRandom())