题目描述:
设计一个支持在平均 时间复杂度 O(1) 下, 执行以下操作的数据结构。
注意: 允许出现重复元素。
insert(val):向集合中插入元素 val。
remove(val):当 val 存在时,从集合中移除一个 val。
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();
方法1:
主要思路:
(1)首先,实现O(1)的查询,直接能想到的就是使用哈希存储,实现O(1)的随机访问,想到的使用数组进行元素的存储,想让这两个存储联合到一起,考虑使用哈希存储数组元素对应的索引(因为这里考虑到有重复的元素,故这里最终需要一个键映射一个存储结构内);
()最终使用的存储结构是 vector 配合 unordered_map<int,unordered_set>实现需要的功能;
class RandomizedCollection {
public:
//存储元素的数据结构
vector<int> nums;
unordered_map<int,unordered_set<int>> mp;
/** 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) {
nums.push_back(val);//将所有的元素存储到数组中
mp[val].insert(nums.size()-1);//将数组中的元素和其对应的索引放入到存储map中
return mp[val].size()==1;//若键对应的set中只有一个元素,说明是第一次插入,故返回true,否则返回false;
}
/** Removes a value from the collection. Returns true if the collection contained the specified element. */
bool remove(int val) {
if(mp.count(val)==0){//若map中不存在给定的元素,则直接返回false
return false;
}
//在map中找出一个要删除的元素对应的在vector中的索引
int idx=*(mp[val].begin());
//这里通过对数组元素的覆盖,实现了vector中删除元素的O(1)
nums[idx]=nums.back();
mp[val].erase(idx);//删除对应的索引
mp[nums[idx]].erase(nums.size()-1);//删除变换位置后的元素的索引
if(idx!=nums.size()-1){//若两个索引指向的不是同一个位置,则需要将覆盖的索引进行插入
mp[nums[idx]].insert(idx);
}
if(mp[val].size()==0){//若被覆盖的值对应的索引数量已经为0,则说明已经在数组中被全部删除,则需要在map中删除
mp.erase(val);
}
nums.pop_back();//将数组中的最后一个元素弹出
return true;
}
/** Get a random element from the collection. */
int getRandom() {
return nums[rand()%nums.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();
*/