def__init__(self): """ Initialize your data structure here. """ self.array = [] self.index_map = {}
definsert(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 """ if val inself.index_map: returnFalse self.index_map[val] = len(self.array) self.array.append(val) returnTrue
defremove(self, val): """ Removes a value from the set. Returns true if the set contained the specified element. :type val: int :rtype: bool """ if val notinself.index_map: returnFalse self.array[self.index_map[val]] = self.array[-1] self.index_map[self.array[-1]] = self.index_map[val] self.array.pop() self.index_map.pop(val) returnTrue
defgetRandom(self): """ Get a random element from the set. :rtype: int """ rnd = random.randint(0, len(self.array)-1) returnself.array[rnd]
# 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()