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

设计一个支持在平均 时间复杂度 O(1) , 执行以下操作的数据结构。

注意: 允许出现重复元素。

  1. insert(val):向集合中插入元素 val。
  2. remove(val):当 val 存在时,从集合中移除一个 val。
  3. getRandom:从现有集合中随机获取一个元素。每个元素被返回的概率应该与其在集合中的数量呈线性相关。

示例:

// 初始化一个空的集合。
RandomizedCollection collection = new RandomizedCollection();

// 向集合中插入 1 。返回 true 表示集合不包含 1 。
collection.insert(1);

// 向集合中插入另一个 1 。返回 false 表示集合包含 1 。集合现在包含 [1,1] 。
collection.insert(1);

// 向集合中插入 2 ,返回 true 。集合现在包含 [1,1,2] 。
collection.insert(2);

// getRandom 应当有 2/3 的概率返回 1 ,1/3 的概率返回 2 。
collection.getRandom();

// 从集合中删除 1 ,返回 true 。集合现在包含 [1,2] 。
collection.remove(1);

// getRandom 应有相同概率返回 1 和 2 。
collection.getRandom();
## template ```java class RandomizedCollection { private Map> map; private List list; private Random random; private int size = 0; public RandomizedCollection() { map = new HashMap<>(); list = new ArrayList<>(); random = new Random(); } public boolean insert(int val) { if (map.containsKey(val)) { Set indexes = map.get(val); list.add(size, val); indexes.add(size); size++; return false; } else { Set indexes = new HashSet<>(); map.put(val, indexes); list.add(size, val); indexes.add(size); size++; return true; } } public boolean remove(int val) { if (!map.containsKey(val)) { return false; } Set indexes = map.get(val); if (list.get(size - 1) == val) { indexes.remove(size - 1); size--; } else { Iterator it = indexes.iterator(); int index = it.next(); it.remove(); int last = list.get(size - 1); list.set(index, last); Set set = map.get(last); set.remove(size - 1); set.add(index); size--; } if (indexes.size() == 0) { map.remove(val); } return true; } public int getRandom() { return list.get(random.nextInt(size)); } } /** * Your RandomizedCollection object will be instantiated and called as such: * RandomizedCollection obj = new RandomizedCollection(); * boolean param_1 = obj.insert(val); * boolean param_2 = obj.remove(val); * int param_3 = obj.getRandom(); */ ``` ## 答案 ```java ``` ## 选项 ### A ```java ``` ### B ```java ``` ### C ```java ```