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();

Solution1: HashMap + ArrayList

code

 public class RandomizedCollection {
class Node {
public int value;
public int index;
public Node(int val, int idx) {
value = val;
index = idx;
}
} private Map<Integer, List<Integer>> map;
private List<Node> list;
private Random r; /** Initialize your data structure here. */
public RandomizedCollection() {
map = new HashMap<>();
list = new ArrayList<>();
r = new Random();
} /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
public boolean insert(int val) {
List<Integer> l = map.getOrDefault(val, new ArrayList<>());
l.add(list.size());
map.put(val, l);
list.add(new Node(val, l.size() - 1));
return l.size() == 1;
} /** Removes a value from the collection. Returns true if the collection contained the specified element. */
public boolean remove(int val) {
if (!map.containsKey(val)) return false;
List<Integer> l = map.get(val);
int removeIdx = l.get(l.size() - 1);
Node replaceNode = list.get(list.size() - 1); // deal with HashMap
map.get(replaceNode.value).set(replaceNode.index, removeIdx);
l.remove(l.size() - 1);
if (l.size() == 0) map.remove(val); // deal with List
list.set(removeIdx, replaceNode);
list.remove(list.size() - 1); return true;
} /** Get a random element from the collection. */
public int getRandom() {
return list.get(r.nextInt(list.size())).value;
}
}

[leetcode]381. Insert Delete GetRandom O(1) - Duplicates allowed常数时间插入删除取随机值的更多相关文章

  1. [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 ...

  2. [LeetCode] 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 O(1) 时间插入、删除和获取随机元素 - 允许重复(C++/Java)

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

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

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

  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]380. Insert Delete GetRandom O(1)常数时间插入删除取随机值

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

  8. 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). ...

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

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

随机推荐

  1. Linux命令详解-ftp服务器配置

    1.ftp服务器配置 1.ftp安装: rpm –qa | grep ftp 2.查看安装内容: rpm-ql |more 3.启动ftp服务: service vsftpd start 4.配置文件 ...

  2. keras中调用tensorboard:from keras.callbacks import TensorBoard

    from keras.models import Sequential from keras.layers import Dense from keras.wrappers.scikit_learn ...

  3. 洛谷::P1972 [SDOI2009]HH的项链

    题目背景 无 题目描述 HH 有一串由各种漂亮的贝壳组成的项链.HH 相信不同的贝壳会带来好运,所以每次散步完后,他都会随意取出一段贝壳,思考它们所表达的含义.HH 不断地收集新的贝壳,因此,他的项链 ...

  4. Elasticsearch 全文搜索和keyword search字段的mapping定义

    在ES5.0之前我们对于需要keyword search的字段都是这样定义的: { "field name":{ "type": "string&qu ...

  5. 深入分析Java Web技术内幕 修订版 pdf

    百度网盘:http://pan.baidu.com/s/1slHCCw9

  6. HTML+CSS实现页面

    使用HTML和CSS实现以下页面: 抽屉首页 个人博客首页 小米官网首页 登录注册页面 一.抽屉首页 1.实现目标:https://dig.chouti.com/ 2.代码: HTML: <!- ...

  7. WebLogic 任意文件上传 远程代码执行漏洞 (CVE-2018-2894)------->>>任意文件上传检测POC

    前言: Oracle官方发布了7月份的关键补丁更新CPU(Critical Patch Update),其中针对可造成远程代码执行的高危漏洞 CVE-2018-2894 进行修复: http://ww ...

  8. 《GPU高性能编程CUDA实战》附录一 高级原子操作

    ▶ 本章介绍了手动实现原子操作.重构了第五章向量点积的过程.核心是通过定义结构Lock及其运算,实现锁定,读写,解锁的过程. ● 章节代码 #include <stdio.h> #incl ...

  9. Android应用程序的自动更新升级(自身升级、通过tomcat)(转)

    Android应用程序的自动更新升级(自身升级.通过tomcat) http://blog.csdn.net/mu0206mu/article/details/7204746 刚入手android一个 ...

  10. form表单提交参数封装

    function getFormValues(element,options) { var data = {}; if(element == null || element == undefined) ...