Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit ef86ecb

Browse files
committed
feature: 0380-insert-delete-getrandom-o1.py
1 parent fb3a444 commit ef86ecb

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
from random import choice
2+
3+
4+
class RandomizedSet:
5+
6+
def __init__(self):
7+
self.dict = {}
8+
self.list = []
9+
10+
def insert(self, val: int) -> bool:
11+
if val in self.dict:
12+
return False
13+
14+
self.dict[val] = len(self.list)
15+
self.list.append(val)
16+
17+
return True
18+
19+
def remove(self, val: int) -> bool:
20+
if val not in self.dict:
21+
return False
22+
23+
idx, last_element = self.dict[val], self.list[-1]
24+
self.list[idx], self.dict[last_element] = last_element, idx
25+
self.list.pop()
26+
del self.dict[val]
27+
28+
return True
29+
30+
def getRandom(self) -> int:
31+
return choice(self.list)

0 commit comments

Comments
 (0)