381. O(1) 时间插入、删除和获取随机元素 - 允许重复
class RandomizedCollection:
def __init__(self):
"""
Initialize your data structure here.
"""
self.collection = []
def insert(self, val: int) -> bool:
"""
Inserts a value to the collection. Returns true if the collection did not already contain the specified element.
"""
flag = True if val not in self.collection else False
self.collection.append(val)
return flag
def remove(self, val: int) -> bool:
"""
Removes a value from the collection. Returns true if the collection contained the specified element.
"""
if val in self.collection:
self.collection.remove(val)
return True
return False
def getRandom(self) -> int:
"""
Get a random element from the collection.
"""
return self.collection[random.randint(0, len(self.collection)-1)]
# 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()
平均复杂度为O(n),如果想达到O(1),需要借助哈希表