381.时间插入、删除和获取随机元素-允许重复

题目

设计一个支持在平均 时间复杂度 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();

思路

用一个vector保存所有的键。
用一个哈希表保存键和对应的在vector的下标。
插入:在键对应的下标中加入一个
随机获得:生成随机数在vector中获取一个。
删除:
将vector最后一个元素key取出来,key对应的下标end也取出来。
首先把要删除val的元素在vector中的一个位置idx赋给key,之后在哈希表key的下标中删除end,添加上val的下标idx。从val的下标中删除idx即可。
**这里不太明白的事为什么要有if(idx<end) m[keys[idx]].emplace(idx)一句,如果这句换了位置就不对了,一直没明白`

代码

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
class RandomizedCollection {
public:
unordered_map<int,unordered_set<int>> m;
vector<int> keys;

/** Initialize your data structure here. */
RandomizedCollection() {

}

/** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
bool insert(int val) {
keys.push_back(val);
if(m.find(val)==m.end()){
m[val].emplace(int(keys.size()-1));
return true;
}else{
m[val].emplace(int(keys.size()-1));
return false;
}
}

/** Removes a value from the collection. Returns true if the collection contained the specified element. */
bool remove(int val) {
if(m.find(val)==m.end()) return false;
//取得最后一个key对应的下标end,要删除的元素所有下标的第一个
int end = keys.size() - 1;
int idx = *m[val].begin();
//最后一个key赋值到要删除的位置上,并且最后一个key要删除end这个下标。
keys[idx] = keys.back();
m[keys[idx]].erase(end);
//要删除的元素删除一个下标,如果是最后一个,就把元素从哈细表中删除。
m[val].erase(idx);
if(m[val].empty()) m.erase(val);
//如果删除元素的下标不是最后一个,就把删除的下标赋给原来最后一个key。
if(idx<end) m[keys[idx]].emplace(idx);

keys.pop_back();
return true;
}

/** Get a random element from the collection. */
int getRandom() {
return keys[rand()%keys.size()];
}
};

/**
* Your RandomizedCollection object will be instantiated and called as such:
* RandomizedCollection* obj = new RandomizedCollection();
* bool param_1 = obj->insert(val);
* bool param_2 = obj->remove(val);
* int param_3 = obj->getRandom();
*/
作者

赵业伟

发布于

2021-09-15

更新于

2021-09-15

许可协议

评论