File tree 1 file changed +32
-0
lines changed
0380-insert-delete-getrandom-o1
1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change
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()
You can’t perform that action at this time.
0 commit comments