
设计一个支持在平均 时间复杂度 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();来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/insert-delete-getrandom-o1-duplicates-allowed 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
类似题目:LeetCode 380. 常数时间插入、删除和获取随机元素(哈希+vector)
class RandomizedCollection {
vector<int> arr;
unordered_map<int, unordered_set<int>> m;//数字 - 对应的下标集合
public:
/** 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) {
bool flag = true;
if(m.find(val) != m.end())//存在元素了
flag = false;
arr.push_back(val);//加入元素
m[val].insert(arr.size()-1);//记录位置
return flag;
}
/** 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;
int idx = *m[val].begin();//找到一个待删元素的位置
m[val].erase(m[val].begin());//删除位置记录
if(m[val].empty())
m.erase(val);
int last = arr.back();//数组最后的元素,跟idx位置的元素交换
m[last].insert(idx);//跟下一句顺序不能变,如果是同一位置就会出错
m[last].erase(arr.size()-1);
if(m[last].empty())
m.erase(last);
arr[idx] = last;//跟新idx位置的元素为 last
arr.pop_back();//last实际为要删除的元素,pop删除
return true;
}
/** Get a random element from the collection. */
int getRandom() {
int idx = random() % arr.size();
return arr[idx];
}
};88 ms 26.5 MB