Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class RandomizedCollection:
- def __init__(self):
- self.hashmap = defaultdict(set)
- self.list = []
- def insert(self, val: int) -> bool:
- self.hashmap[val].add(len(self.list))
- self.list.append(val)
- return len(self.hashmap[val]) == 1
- def remove(self, val: int) -> bool:
- if self.hashmap[val]:
- indexes = self.hashmap[val]
- index = indexes.pop()
- last = self.list[-1]
- self.list[index] = last
- self.hashmap[last].add(index)
- self.hashmap[last].remove(len(self.list)-1)
- self.list.pop()
- return True
- return False
- def getRandom(self) -> int:
- return random.choice(self.list)
- # Your RandomizedCollection object will be instantiated and called as such:
- # obj = RandomizedCollection()
- # param_1 = obj.insert(val)
- # param_2 = obj.remove(val)
- # param_3 = obj.getRandom()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement