归档

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

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] (getRandom 的输出可能是 1 或 2)

提示:

  • -2^31 <= val <= 2^31 - 1
  • 最多调用 insert、remove 和 getRandom 函数 2 * 10^5 次
  • 在调用 getRandom 方法时,数据结构中 至少 存在一个元素。

题解

为什么需要数组和哈希表配合

哈希表适合判断一个值是否存在,但不能直接按随机下标访问元素;动态数组可以按下标访问,但按值查找、删除中间元素通常需要线性时间。本题不要求保持元素顺序,可以让两者配合:nums 保存当前所有不同的值,indices 保存“值 → 在 nums 中的下标”。两份数据必须始终对应。

插入时,先查哈希表。如果值已存在,返回 false;否则记录它将被追加到的下标 nums.size(),再追加到数组,返回 true。

删除时用末尾元素填补空位

删除中间项时,不必让后面所有元素向前移动。先从哈希表找到待删下标,把数组末项写到这个位置,并更新末项的下标;然后删除原末项,再移除待删值的映射。

例如 nums = [10,20,30],删除 20:把 30 写到下标 1,更新 indices[30] = 1,删除末项后得到 [10,30],最后移除 20 的映射。如果删除的本来就是末项,lastElement 就是 val,覆盖和更新都发生在同一个位置,随后删除末项仍然正确;只剩一个元素时也一样。这种情况下 indices.put(lastElement, index) 会先把 val 的映射写回去,所以 indices.remove(val) 必须放在它之后执行,否则会留下一条指向已删除位置的映射。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public boolean remove(int val) {
    if (!indices.containsKey(val)) {
        return false;
    }

    int index = indices.get(val);
    int lastElement = nums.get(nums.size() - 1);

    nums.set(index, lastElement);
    indices.put(lastElement, index);

    nums.remove(nums.size() - 1);
    indices.remove(val);

    return true;
}

哈希表的查找、插入和删除为平均常数时间,动态数组追加为摊还常数时间。交换后删除末项不会移动其余元素,随机访问也是常数时间。集合大小为 n 时,数组与映射占 O(n) 空间。

等概率随机返回

getRandom 在 [0, nums.size()) 内等概率选一个整数下标,再返回对应值。每个值在数组中恰好占一个位置,所以被返回的概率都为 1 / nums.size()。删除虽然改变了顺序,但没有产生空洞或重复值,不影响这个结论。题目保证调用随机方法时集合非空。

完整示例

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import java.util.*;

public class Main {

    static class RandomizedSet {
        private final List<Integer> nums;
        private final Map<Integer, Integer> indices;
        private final Random random;

        public RandomizedSet() {
            nums = new ArrayList<>();
            indices = new HashMap<>();
            random = new Random();
        }

        public boolean insert(int val) {
            if (indices.containsKey(val)) {
                return false;
            }

            indices.put(val, nums.size());
            nums.add(val);
            return true;
        }

        public boolean remove(int val) {
            if (!indices.containsKey(val)) {
                return false;
            }

            int index = indices.get(val);
            int lastElement = nums.get(nums.size() - 1);

            nums.set(index, lastElement);
            indices.put(lastElement, index);

            nums.remove(nums.size() - 1);
            indices.remove(val);
            return true;
        }

        public int getRandom() {
            return nums.get(random.nextInt(nums.size()));
        }
    }

    public static void main(String[] args) {
        System.out.println("开始测试 RandomizedSet:");

        RandomizedSet set = new RandomizedSet();

        System.out.println("insert(1): " + set.insert(1));
        System.out.println("remove(2): " + set.remove(2));
        System.out.println("insert(2): " + set.insert(2));
        System.out.println("getRandom(): " + set.getRandom());
        System.out.println("remove(1): " + set.remove(1));
        System.out.println("insert(2): " + set.insert(2));
        System.out.println("getRandom(): " + set.getRandom());
    }
}

运行结果(OpenJDK 21.0.12):

1
2
3
4
5
6
7
8
开始测试 RandomizedSet:
insert(1): true
remove(2): false
insert(2): true
getRandom(): 1
remove(1): true
insert(2): false
getRandom(): 2

getRandom() 每次运行的结果可能不同:第一次调用时集合是 {1, 2},返回 1 或 2 都正确;第二次调用时集合只剩 {2},只能返回 2。

本文由作者按照 CC BY 4.0 进行授权