@[toc](380. O(1) 时间插入、删除和获取随机元素)
题目描述
实现RandomizedSet 类:
- RandomizedSet() 初始化 RandomizedSet 对象
- bool insert(int val) 当元素 val 不存在时,向集合中插入该项,并返回 true ;否则,返回 false 。
- bool remove(int val) 当元素 val 存在时,从集合中移除该项,并返回 true ;否则,返回 false 。
- int getRandom() 随机返回现有集合中的一项(测试用例保证调用此方法时集合中至少存在一个元素)。每个元素应该有 相同的概率 被返回。
你必须实现类的所有函数,并满足每个函数的 平均 时间复杂度为 O(1) 。
示例:
输入
["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"]
[[], [1], [2], [2], [], [1], [2], []]
输出
[null, true, false, true, 2, true, false, 2]
解释
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // 向集合中插入 1 。返回 true 表示 1 被成功地插入。
randomizedSet.remove(2); // 返回 false ,表示集合中不存在 2 。
randomizedSet.insert(2); // 向集合中插入 2 。返回 true 。集合现在包含 [1,2] 。
randomizedSet.getRandom(); // getRandom 应随机返回 1 或 2 。
randomizedSet.remove(1); // 从集合中移除 1 ,返回 true 。集合现在包含 [2] 。
randomizedSet.insert(2); // 2 已在集合中,所以返回 false 。
randomizedSet.getRandom(); // 由于 2 是集合中唯一的数字,getRandom 总是返回 2 。
提示:
- -231 <= val <= 231 - 1
- 最多调用 insert、remove 和 getRandom 函数 2 * 105 次
- 在调用 getRandom 方法时,数据结构中 至少存在一个 元素。
题解思路
哈希表 对元素 插入 删除 可以达到o(1) 但是无法在o(1)的时间内随机返回元素
列表 可以在o(1)的时间 返回随机元素, 但是无法在o(1)的时间判断元素是否存在 因此无法完成删除插入操作
因此我们结合哈希表跟列表来设计我们的数据结构
- 插入
- 如果值不存在在哈希表中
- 我们将值插入到数组中
- 同时将数组下标跟值插入到哈希表中
- 删除
- 在哈希表中找到值及其对应的下标
- 在数组中将对应下标处的值改为数组中最后一个元素的值
- 在字典中将该值对应的下标也进行修改
题解代码
class RandomizedSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.l=[]
self.d={}
def insert(self, val: int) -> bool:
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
"""
if val in self.d:
return False
self.d[val]=len(self.l)
self.l.append(val)
return True
def remove(self, val: int) -> bool:
"""
Removes a value from the set. Returns true if the set contained the specified element.
"""
if val not in self.d:
return False
ind=self.d[val]
self.l[ind]=self.l[-1]
self.d[self.l[ind]]=ind
self.l.pop()
del self.d[val]
return True
def getRandom(self) -> int:
"""
Get a random element from the set.
"""
return choice(self.l)