Design a data structure that supports all following operations in average O(1) time.

Note: Duplicate elements are allowed.

  1. insert(val): Inserts an item val to the collection.
  2. remove(val): Removes an item val from the collection if present.
  3. getRandom: Returns a random element from current collection of elements. The probability of each element being returned is linearly related to the number of same value the collection contains.

Example:

// Init an empty collection.
RandomizedCollection collection = new RandomizedCollection(); // Inserts 1 to the collection. Returns true as the collection did not contain 1.
collection.insert(1); // Inserts another 1 to the collection. Returns false as the collection contained 1. Collection now contains [1,1].
collection.insert(1); // Inserts 2 to the collection, returns true. Collection now contains [1,1,2].
collection.insert(2); // getRandom should return 1 with the probability 2/3, and returns 2 with the probability 1/3.
collection.getRandom(); // Removes 1 from the collection, returns true. Collection now contains [1,2].
collection.remove(1); // getRandom should return 1 and 2 both equally likely.
collection.getRandom();

Approach #1: C++.

class RandomizedCollection {
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) {
auto result = m.find(val) == m.end(); m[val].push_back(nums.size());
nums.push_back(pair<int, int>(val, m[val].size() - 1)); return result;
} /** Removes a value from the collection. Returns true if the collection contained the specified element. */
bool remove(int val) {
if (!m.count(val)) return false;
else {
auto last = nums.back();
m[last.first][last.second] = m[val].back();
nums[m[val].back()] = last;
m[val].pop_back();
if (m[val].empty()) m.erase(val);
nums.pop_back();
return true;
}
} /** Get a random element from the collection. */
int getRandom() {
return nums[rand() % nums.size()].first;
}
private:
vector<pair<int, int>> nums;
unordered_map<int, vector<int>> m;
}; /**
* 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();
*/

  

In this solution we use vector<pair<int, int>> nums to resoter the numbers in the set,  using the unordered_map<int, vector<int>> to restore the position of the number.

Runtime: 36 ms, faster than 82.83% of C++ online submissions for Insert Delete GetRandom O(1) - Duplicates allowed.

381. Insert Delete GetRandom O(1) - Duplicates allowed的更多相关文章

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

    380. Insert Delete GetRandom O(1) 实现插入.删除.获得随机数功能,且时间复杂度都在O(1).实际上在插入.删除两个功能中都包含了查找功能,当然查找也必须是O(1). ...

  2. [LeetCode] 381. Insert Delete GetRandom O(1) - Duplicates allowed 常数时间内插入删除和获得随机数 - 允许重复

    Design a data structure that supports all following operations in average O(1) time. Note: Duplicate ...

  3. [LeetCode] 381. Insert Delete GetRandom O(1) - Duplicates allowed 插入删除和获得随机数O(1)时间 - 允许重复

    Design a data structure that supports all following operations in average O(1) time. Note: Duplicate ...

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

    原题链接在这里:https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/?tab=Description ...

  5. LeetCode 381. Insert Delete GetRandom O(1) - Duplicates allowed O(1) 时间插入、删除和获取随机元素 - 允许重复(C++/Java)

    题目: Design a data structure that supports all following operations in averageO(1) time. Note: Duplic ...

  6. LeetCode 381. Insert Delete GetRandom O(1) - Duplicates allowed (插入删除和获得随机数 常数时间 允许重复项)

    Design a data structure that supports all following operations in average O(1) time. Note: Duplicate ...

  7. [leetcode]381. Insert Delete GetRandom O(1) - Duplicates allowed常数时间插入删除取随机值

    Design a data structure that supports all following operations in average O(1) time. Note: Duplicate ...

  8. 381. Insert Delete GetRandom O(1) - Duplicates allowed允许重复的设计1数据结构

    [抄题]: Design a data structure that supports all following operations in average O(1) time. Note: Dup ...

  9. 381 Insert Delete GetRandom O(1) - Duplicates allowed O(1) 时间插入、删除和获取随机元素 - 允许重复

    设计一个支持在平均 时间复杂度 O(1) 下, 执行以下操作的数据结构.注意: 允许出现重复元素.    insert(val):向集合中插入元素 val.    remove(val):当 val ...

随机推荐

  1. Linux把查询结果写入到文本

    在Linux命令模式下,可以将查询结果写入文件.大概有两种方式,增量写入和覆盖写入. 增量写入: #iostat -m >> /tmp/iostat.txt 覆盖写入: #iostat - ...

  2. 【BZOJ2161】布娃娃 扫描线+线段树

    [BZOJ2161]布娃娃 Description 小时候的雨荨非常听话,是父母眼中的好孩子.在学校是老师的左右手,同学的好榜样.后来她成为艾利斯顿第二代考神,这和小时候培养的良好素质是分不开的.雨荨 ...

  3. mac gem命令

    $ gem sources -r https://rubygems.org/ (移除旧版本的镜像,如果你不知道你电脑上目前用的是什么镜像,可用  $ gem sources -l  来查看)  $ g ...

  4. 6.5.1.3 Caching SHA-2 Pluggable Authentication

    MySQL :: MySQL 8.0 Reference Manual :: 6.5.1.3 Caching SHA-2 Pluggable Authentication https://dev.my ...

  5. java内存泄露具体解释

    非常多人有疑问,java有非常好的垃圾回收机制,怎么会有内存泄露?事实上是有的,那么何为内存泄露?在Java中所谓内存泄露就是指在程序执行的过程中产生了一些对象,当不须要这些对象时,他们却没有被垃圾回 ...

  6. [自动化平台系列] - 初次使用 Macaca-前端自动化测试(2)

    接一下来讲一讲api的使用   http://macacajs.github.io/macaca-wd/api/ var _config = { //本程序的host host: 'http://te ...

  7. 对私有API提交的注意事项

    1.这个等于堵死了调试断点.关闭就不能断点调试了. 2.对于敏感的函数名要做一个对称加密处理. 防止二进制文件的静态扫描. 3.对于调用私有函数的方法,可以做一个宏定义包装. #define 你的正常 ...

  8. Vue 组件实例属性的使用

    前言 因为最近面试了二.三十个人,发现大部分都还是只是停留在 Vue 文档的教程.有部分连教程这部分的文档也没看全.所以稍微写一点,让新上手的 Vuer 多了解 Vue 文档的其他更需要关注的点. 因 ...

  9. HDU5171 GTY's birthday gift —— 矩阵快速幂

    题目链接:https://vjudge.net/problem/HDU-5171 GTY's birthday gift Time Limit: 2000/1000 MS (Java/Others)  ...

  10. Java Web 项目打包脚本

    可用于 (但不限于) Eclipse 项目. 一次性生成:1. Java doc .zip 包:2. Java 源代码 .zip 包:3. Java 二进制文件 .jar 包:4. Java 源代码加 ...