LeetCode 题解工作台
O(1) 时间插入、删除和获取随机元素
实现 RandomizedSet 类: RandomizedSet() 初始化 RandomizedSet 对象 bool insert(int val) 当元素 val 不存在时,向集合中插入该项,并返回 true ;否则,返回 false 。 bool remove(int val) 当元素 v…
5
题型
7
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
我们定义一个动态列表 ,用于存储集合中的元素,定义一个哈希表 ,用于存储每个元素在 中的下标。 插入元素时,如果元素已经存在于哈希表 中,直接返回 `false`;否则,我们将元素插入到动态列表 的末尾,同时将元素和其在 中的下标插入到哈希表 中,最后返回 `true`。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
实现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方法时,数据结构中 至少存在一个 元素。
解题思路
方法一:哈希表 + 动态列表
我们定义一个动态列表 ,用于存储集合中的元素,定义一个哈希表 ,用于存储每个元素在 中的下标。
插入元素时,如果元素已经存在于哈希表 中,直接返回 false;否则,我们将元素插入到动态列表 的末尾,同时将元素和其在 中的下标插入到哈希表 中,最后返回 true。
删除元素时,如果元素不存在于哈希表 中,直接返回 false;否则,我们从哈希表中获取元素在列表 中的下标 ,然后将列表 的最后一个元素 与 交换,然后将哈希表中 的下标更新为 ,最后将 的最后一个元素删除,同时将元素从哈希表中删除,最后返回 true。
获取随机元素时,我们从动态列表 中随机选择一个元素返回即可。
时间复杂度 ,空间复杂度 。其中 为集合中元素的个数。
class RandomizedSet:
def __init__(self):
self.d = {}
self.q = []
def insert(self, val: int) -> bool:
if val in self.d:
return False
self.d[val] = len(self.q)
self.q.append(val)
return True
def remove(self, val: int) -> bool:
if val not in self.d:
return False
i = self.d[val]
self.d[self.q[-1]] = i
self.q[i] = self.q[-1]
self.q.pop()
self.d.pop(val)
return True
def getRandom(self) -> int:
return choice(self.q)
# 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()
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity for insert, remove, and getRandom is average O(1) because array access and hash map operations are constant. Space complexity is O(n) for storing elements and indices. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Looking for true O(1) operations on all functions, not amortized linear time.
- question_mark
Expect awareness of hash map collisions and edge cases during deletion.
- question_mark
Interested in random selection correctness and uniform probability in getRandom.
常见陷阱
外企场景- error
Swapping incorrectly during remove can break index mapping and cause wrong deletions.
- error
Forgetting to update the hash map when moving the last element leads to inconsistent state.
- error
Using only a hash set without an array prevents O(1) random access.
进阶变体
外企场景- arrow_right_alt
Randomized collection allowing duplicates with getRandom weighted by occurrence.
- arrow_right_alt
Implementing similar O(1) operations for a fixed-size window or sliding set.
- arrow_right_alt
Extending to support getRandomSubset(k) efficiently from the current set.