LeetCode 381. Insert Delete GetRandom O(1) - Duplicates allowed
原题链接
困难
作者:
徐辰潇
,
2020-06-15 06:06:21
,
所有人可见
,
阅读 545
class RandomizedCollection:
#TC: O(1) for all operations
#SC: O(n)
def __init__(self):
"""
Initialize your data structure here.
"""
self.val_idx = collections.defaultdict(set)
self.idx_val = {}
self.count = 0
def insert(self, val: int) -> bool:
"""
Inserts a value to the collection. Returns true if the collection did not already contain the specified element.
"""
self.count += 1
Bool = True
if val in self.val_idx:
Bool = False
self.val_idx[val].add(self.count)
self.idx_val[self.count] = val
return Bool
def remove(self, val: int) -> bool:
"""
Removes a value from the collection. Returns true if the collection contained the specified element.
"""
if val not in self.val_idx:
return False
else:
gap_idx = self.val_idx[val].pop()
if len(self.val_idx[val]) == 0:
del self.val_idx[val]
if gap_idx != self.count:
move_val = self.idx_val[self.count]
self.val_idx[move_val].remove(self.count)
self.val_idx[move_val].add(gap_idx)
self.idx_val[gap_idx] = move_val
del self.idx_val[self.count]
self.count -= 1
return True
def getRandom(self) -> int:
"""
Get a random element from the collection.
"""
rand = randint(1, self.count)
return self.idx_val[rand]
# 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()