Python | Leetcode Python题解之第380题O(1)时间插入、删除和获取随机元素
题目:
题解:
class RandomizedSet:
def __init__(self):
self.nums = []
self.indices = {}
def insert(self, val: int) -> bool:
if val in self.indices:
return False
self.indices[val] = len(self.nums)
self.nums.append(val)
return True
def remove(self, val: int) -> bool:
if val not in self.indices:
return False
id = self.indices[val]
self.nums[id] = self.nums[-1]
self.indices[self.nums[id]] = id
self.nums.pop()
del self.indices[val]
return True
def getRandom(self) -> int:
return choice(self.nums)