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快捷键和vim快捷键

    系统下常用快捷键   ctrl+左右键      在单词之间跳转 Ctrl + a            光标移动到行首(ahead of line),相当于通常的Home键 Ctrl + e     ...

  2. 左儿子右兄弟Trie UVA 11732 strcmp() Anyone?

    题目地址: option=com_onlinejudge&Itemid=8&category=117&page=show_problem&problem=2832&qu ...

  3. [Phoenix] 七、如何使用自增ID

    摘要: 在传统关系型数据库中设计主键时,自增ID经常被使用.不仅能够保证主键的唯一,同时也能简化业务层实现.Phoenix怎么使用自增ID,是我们这篇文章的重点. 在传统关系型数据库中设计主键时,自增 ...

  4. 2018-11-9-匿名函数&递归函数初识

    1.匿名函数(lambda) 2.递归函数初识

  5. TEdit的创建与显示过程

    -------------------------- 分析TEdit的创建与显示过程 --------------------------TCustomEdit = class(TWinControl ...

  6. ABAP抓取异常 try ,endtry.

    DATA: O_CX TYPE REF TO CX_ROOT. TRY . MOVE LS_UPLOAD-MENGE TO LS_OUTPUT-MENGE. CATCH CX_ROOT INTO O_ ...

  7. R in Action(0) 开篇

    这几年数据挖掘的火热,也越来越多的人把R作为数据挖掘的一个辅助工具,据国际性组织kkguter统计有60%的人在挖掘过程中用到R工具,可见这个工具是多么的流行,对于数据统计.筛选以及画图绝对是神器.尽 ...

  8. win7 64位系统与Ubuntu14.04 64位系统双系统安装【转】

    本文转载自:http://blog.csdn.net/strugglepeach/article/details/51260886 Window 7 + Ubuntu 双系统安装   硬件: Thin ...

  9. javascript ajax和jquery ajax

    一 进行ajax步骤: 1 获取dom值 2发送ajax请求 3返回成功进行前端逻辑处理 二 原生javascript的ajax <!DOCTYPE html> <html> ...

  10. 基于BASYS2的VHDL程序与烧写——按键消抖程序

    请尊重作者版权,转载请注明源地址http://www.cnblogs.com/connorzx/p/3548364.html 按键在按下的过程中通常会产生一段时间的抖动,为了消除这种抖动,一般采取两种 ...