Skip to content

Commit cb1ec53

Browse files
committed
Time: 255 ms (72.29%), Space: 63.9 MB (28.89%) - LeetHub
1 parent 76f1bda commit cb1ec53

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class RandomizedSet:
2+
3+
def __init__(self):
4+
self.dict = {}
5+
self.list = []
6+
7+
def insert(self, val: int) -> bool:
8+
if val in self.dict:
9+
return False
10+
self.dict[val] = len(self.list)
11+
self.list.append(val)
12+
return True
13+
14+
def remove(self, val: int) -> bool:
15+
if val not in self.dict:
16+
return False
17+
idx = self.dict[val]
18+
last_element = self.list[-1]
19+
self.list[idx] = last_element
20+
self.dict[last_element] = idx
21+
self.list.pop()
22+
del self.dict[val]
23+
return True
24+
25+
def getRandom(self) -> int:
26+
return random.choice(self.list)
27+
28+
# Your RandomizedSet object will be instantiated and called as such:
29+
# obj = RandomizedSet()
30+
# param_1 = obj.insert(val)
31+
# param_2 = obj.remove(val)
32+
# param_3 = obj.getRandom()

0 commit comments

Comments
 (0)