-
Notifications
You must be signed in to change notification settings - Fork 0
/
Insert Delete GetRandom O(1).py
50 lines (45 loc) · 1.66 KB
/
Insert Delete GetRandom O(1).py
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
import random
class RandomizedSet:
def __init__(self):
self.elements=[]
self.mapping={} #ele -> idx
self.size=0
def insert(self, val: int) -> bool:
if(val in self.mapping):
#already present
return False
idx=self.size
self.elements.append(val) #add val to list
self.mapping[val]=idx #create mapping
self.size+=1 #increment size
return True
def remove(self, val: int) -> bool:
if(val not in self.mapping):
#element not present
return False
self.moveToEndAndRemove(val) #IMP, move val to end of elements!
return True
def moveToEndAndRemove(self,currEle):
currIdx=self.mapping[currEle]
lastEle=self.elements[-1]
lastIdx=self.size-1
if(currIdx==lastIdx):
self.elements.pop()
del self.mapping[currEle]
else:
#swap element with the last element, pop off element from end and update mapping
self.elements[currIdx],self.elements[lastIdx]=self.elements[lastIdx],self.elements[currIdx]
#pop off val from end!
self.elements.pop()
del self.mapping[currEle] #remove mapping of currEle
self.mapping[lastEle]=currIdx #update mapping
self.size-=1 #decrement size
def getRandom(self) -> int:
#return random.choice(self.elements)
idx=random.randint(0,self.size-1)
return self.elements[idx]
# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()