-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertDeleteRandom.py
More file actions
49 lines (40 loc) · 1.36 KB
/
insertDeleteRandom.py
File metadata and controls
49 lines (40 loc) · 1.36 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
#this solution is O(n)
import random
class RandomizedSet:
def __init__(self):
self.data = []
self.map = {}
#key in map is element in data, val is index
def insert(self, val: int) -> bool:
if val in self.map:
return False
self.map[val] = len(self.data)
#add to the list. by doing so I connect
#the dict and the list
self.data.append(val)
return True
def remove(self, val: int) -> bool:
if not val in self.map:
return False
backend_digit = self.data[-1]
item_remove = self.map[val]
print(backend_digit)
print(item_remove)
#look at contruct below
self.map[backend_digit] = item_remove
self.data[item_remove] = backend_digit
self.data.pop()
self.map.pop(val)
return True
def getRandom(self) -> bool:
return random.choice(self.data)
random = RandomizedSet()
param_1 = random.insert(4) #true
param_2 = random.remove(7) #false
param_3 = random.insert(8)
param_4 = random.insert(3) #true now 1,2
param_5 = random.insert(9)
param_6 = random.getRandom() #return either 1 or 2
param_7 = random.remove(8) #true now only 2 left
param_8 = random.insert(5) #false 2 already in set
param_9 = random.getRandom() #only 2 left so return 2