[LeetCode] 381. Insert Delete GetRandom O(1) - Duplicates allowed

RandomizedCollection is a data structure that contains a collection of numbers, possibly duplicates (i.e., a multiset). It should support inserting and removing specific elements and also removing a random element.

Implement the RandomizedCollection class:

  • RandomizedCollection() Initializes the empty RandomizedCollection object.
  • bool insert(int val) Inserts an item val into the multiset, even if the item is already present. Returns true if the item is not present, false otherwise.
  • bool remove(int val) Removes an item val from the multiset if present. Returns true if the item is present, false otherwise. Note that if val has multiple occurrences in the multiset, we only remove one of them.
  • int getRandom() Returns a random element from the current multiset of elements. The probability of each element being returned is linearly related to the number of same values the multiset contains.

You must implement the functions of the class such that each function works on average O(1) time complexity.

Note: The test cases are generated such that getRandom will only be called if there is at least one item in the RandomizedCollection.

Example 1:

Input
["RandomizedCollection", "insert", "insert", "insert", "getRandom", "remove", "getRandom"]
[[], [1], [1], [2], [], [1], []]
Output
[null, true, false, true, 2, true, 1]

Explanation
RandomizedCollection randomizedCollection = new RandomizedCollection();
randomizedCollection.insert(1);   // return true since the collection does not contain 1.
                                  // Inserts 1 into the collection.
randomizedCollection.insert(1);   // return false since the collection contains 1.
                                  // Inserts another 1 into the collection. Collection now contains [1,1].
randomizedCollection.insert(2);   // return true since the collection does not contain 2.
                                  // Inserts 2 into the collection. Collection now contains [1,1,2].
randomizedCollection.getRandom(); // getRandom should:
                                  // - return 1 with probability 2/3, or
                                  // - return 2 with probability 1/3.
randomizedCollection.remove(1);   // return true since the collection contains 1.
                                  // Removes 1 from the collection. Collection now contains [1,2].
randomizedCollection.getRandom(); // getRandom should return 1 or 2, both equally likely.

Constraints:

  • -231 <= val <= 231 - 1
  • At most 2 * 105 calls in total will be made to insertremove, and getRandom.
  • There will be at least one element in the data structure when getRandom is called.

O(1) 时间插入、删除和获取随机元素 - 允许重复。

RandomizedCollection 是一种包含数字集合(可能是重复的)的数据结构。它应该支持插入和删除特定元素,以及删除随机元素。

实现 RandomizedCollection 类:

RandomizedCollection()初始化空的 RandomizedCollection 对象。
bool insert(int val) 将一个 val 项插入到集合中,即使该项已经存在。如果该项不存在,则返回 true ,否则返回 false 。
bool remove(int val) 如果存在,从集合中移除一个 val 项。如果该项存在,则返回 true ,否则返回 false 。注意,如果 val 在集合中出现多次,我们只删除其中一个。
int getRandom() 从当前的多个元素集合中返回一个随机元素。每个元素被返回的概率与集合中包含的相同值的数量 线性相关 。
您必须实现类的函数,使每个函数的 平均 时间复杂度为 O(1) 。

注意:生成测试用例时,只有在 RandomizedCollection 中 至少有一项 时,才会调用 getRandom 。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/insert-delete-getrandom-o1-duplicates-allowed
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题意跟380题很接近,唯一不同的条件是这个题允许加入相同元素。

思路还是用 hashmap + arrayList,hashmap 的 key 是每个不同的数字,value 是一个 hashset,存的是每个数字在 list 里的 index。

insert() - 遇到相同的数字的时候,每次记得先在 hashmap 的 key 中加入 list 当前的 size 再处理 list 的部分。arrayList 还是保存每一个被加入的 num。

remove() - 从 hashmap 里删除的时候,如果某个元素出现过多次,则删除一次就好,此时需要对 hashset 做 iterate;如果这个元素只出现了一次,记得要将 hashmap 中的 key 也一并删除。对 list 做删除操作的时候,跟 380 题一样,也是需要把 list 的最后一个元素移动到 list 里被删除的元素的位置上。

时间O(1) - required

空间O(n)

Java实现

 1 class RandomizedCollection {
 2     HashMap<Integer, HashSet<Integer>> map;
 3     List<Integer> list;
 4     Random rmd;
 5 
 6     /** Initialize your data structure here. */
 7     public RandomizedCollection() {
 8         map = new HashMap<>();
 9         list = new ArrayList<>();
10         rmd = new Random();
11     }
12     
13     /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
14     public boolean insert(int val) {
15         boolean contain = map.containsKey(val);
16         if (!contain) {
17             map.put(val, new HashSet<>());
18         }
19         map.get(val).add(list.size());
20         list.add(val);
21         return !contain;
22     }
23     
24     /** Removes a value from the collection. Returns true if the collection contained the specified element. */
25     public boolean remove(int val) {
26         if (!map.containsKey(val)) {
27             return false;
28         }
29         int firstIndex = map.get(val).iterator().next();
30         map.get(val).remove(firstIndex);
31         if (map.get(val).size() == 0) {
32             map.remove(val);
33         }
34         int lastVal = list.remove(list.size() - 1);
35         if (firstIndex != list.size()) {
36             list.set(firstIndex, lastVal);
37             map.get(lastVal).remove(list.size());
38             map.get(lastVal).add(firstIndex);
39         }
40         return true;
41     }
42     
43     /** Get a random element from the collection. */
44     public int getRandom() {
45         return list.get(rmd.nextInt(list.size()));
46     }
47 }
48 
49 /**
50  * Your RandomizedCollection object will be instantiated and called as such:
51  * RandomizedCollection obj = new RandomizedCollection();
52  * boolean param_1 = obj.insert(val);
53  * boolean param_2 = obj.remove(val);
54  * int param_3 = obj.getRandom();
55  */

 

相关题目

380. Insert Delete GetRandom O(1)

381. Insert Delete GetRandom O(1) - Duplicates allowed

LeetCode 题目总结

posted @ 2020-06-13 10:46  CNoodle  阅读(144)  评论(0编辑  收藏  举报