-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy path380_insert_delete_getrandom_o1.py
More file actions
50 lines (42 loc) · 1.17 KB
/
380_insert_delete_getrandom_o1.py
File metadata and controls
50 lines (42 loc) · 1.17 KB
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
42
43
44
45
46
47
48
49
50
"""
Your RandomizedSet object will be instantiated and called as such:
obj = RandomizedSet()
param = obj.insert(val)
param = obj.remove(val)
param = obj.getRandom()
"""
import random
class RandomizedSet:
def __init__(self):
self.nums = []
self.val2idx = {}
def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
:type val: int
:rtype: bool
"""
self.val2idx[val] = len(self.nums)
self.nums.append(val)
def remove(self, val):
"""
Removes a value from the set. Returns true if the set contained the specified element.
:type val: int
:rtype: bool
"""
if val not in self.val2idx:
return False
i = self.val2idx[val]
key = self.nums[-1]
self.val2idx[key] = i
self.nums[i] = self.nums[-1]
self.nums.pop()
del self.val2idx[val]
return True
def getRandom(self):
"""
Get a random element from the set.
:rtype: int
"""
i = random.randrange(len(self.nums))
return self.nums[i]