LeetCode 题解工作台

O(1) 时间插入、删除和获取随机元素

实现 RandomizedSet 类: RandomizedSet() 初始化 RandomizedSet 对象 bool insert(int val) 当元素 val 不存在时,向集合中插入该项,并返回 true ;否则,返回 false 。 bool remove(int val) 当元素 v…

category

5

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·哈希·扫描

bolt

答案摘要

我们定义一个动态列表 ,用于存储集合中的元素,定义一个哈希表 ,用于存储每个元素在 中的下标。 插入元素时,如果元素已经存在于哈希表 中,直接返回 `false`;否则,我们将元素插入到动态列表 的末尾,同时将元素和其在 中的下标插入到哈希表 中,最后返回 `true`。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

实现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
  • 最多调用 insertremovegetRandom 函数 2 * 105
  • 在调用 getRandom 方法时,数据结构中 至少存在一个 元素。
lightbulb

解题思路

方法一:哈希表 + 动态列表

我们定义一个动态列表 qq,用于存储集合中的元素,定义一个哈希表 dd,用于存储每个元素在 qq 中的下标。

插入元素时,如果元素已经存在于哈希表 dd 中,直接返回 false;否则,我们将元素插入到动态列表 qq 的末尾,同时将元素和其在 qq 中的下标插入到哈希表 dd 中,最后返回 true

删除元素时,如果元素不存在于哈希表 dd 中,直接返回 false;否则,我们从哈希表中获取元素在列表 qq 中的下标 ii,然后将列表 qq 的最后一个元素 q[1]q[-1]q[i]q[i] 交换,然后将哈希表中 q[1]q[-1] 的下标更新为 ii,最后将 qq 的最后一个元素删除,同时将元素从哈希表中删除,最后返回 true

获取随机元素时,我们从动态列表 qq 中随机选择一个元素返回即可。

时间复杂度 O(1)O(1),空间复杂度 O(n)O(n)。其中 nn 为集合中元素的个数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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()
speed

复杂度分析

指标
时间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
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

O(1) 时间插入、删除和获取随机元素题解:数组·哈希·扫描 | LeetCode #380 中等