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

题目:

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

题解:

用set来保存val的所有index.

Time Complexity: insert, O(1). remove, O(1). getRandom, O(1).

Space: O(n).

AC Java:

 class RandomizedCollection {
ArrayList<Integer> list;
HashMap<Integer, LinkedHashSet<Integer>> numToInds; /** Initialize your data structure here. */
public RandomizedCollection() {
list = new ArrayList<>();
numToInds = new HashMap<>();
} /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
public boolean insert(int val) {
boolean contains = numToInds.containsKey(val);
if(!contains){
numToInds.put(val, new LinkedHashSet<Integer>());
} numToInds.get(val).add(list.size());
list.add(val);
return contains;
} /** Removes a value from the collection. Returns true if the collection contained the specified element. */
public boolean remove(int val) {
if(!numToInds.containsKey(val) || numToInds.get(val).size() == 0){
return false;
} LinkedHashSet<Integer> lhs = numToInds.get(val);
int ind = lhs.iterator().next();
lhs.remove(ind);
int last = list.get(list.size() - 1);
list.set(ind, last);
numToInds.get(last).add(ind);
numToInds.get(last).remove(list.size() - 1);
list.remove(list.size() - 1);
return true;
} /** Get a random element from the collection. */
public int getRandom() {
Random rand = new Random();
return list.get(rand.nextInt(list.size()));
}
} /**
* Your RandomizedCollection object will be instantiated and called as such:
* RandomizedCollection obj = new RandomizedCollection();
* boolean param_1 = obj.insert(val);
* boolean param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/

类似Insert Delete GetRandom O(1).

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

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

  2. 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 ...

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

  4. 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 ...

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

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

  7. 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 O(1) 时间插入、删除和获取随机元素 - 允许重复

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

  9. 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 ...

随机推荐

  1. Qt 自定义QTabWidget

    思路: QTabWidget的特点:点击不同的选项卡显示不同的窗口.可以将QTabWidget分成两部分: (1).选项卡:点击时要知道点击的是哪个选项.则需要将选项卡和窗口的信息存起来,点击时去这个 ...

  2. java笔记4

    private关键字 1.是一个权限修饰符.       2.用于修饰成员       3.被私有化的成员只能在本类中有效 常用之一: -将成员变量私有化,对外提供对应的set,get方法对其进行访问 ...

  3. 在KubeSphere中部署Kubeapps

    1. 情况说明 使用一台VMWare Workstation虚拟机,4核8G内存,50G磁盘 已安装KubeSphere 2.1 版本,已经按照官方文档的入门必读,示例一创建好相应的账号信息等 Kub ...

  4. resnet的理解-- 面试笔记

    上周参加了XX大学研究生推免的面试,面试老爷问到了resnet主要解决了什么问题,我下意识的回答到解决了当网络加深的时候会出现的vanishing/exploding gradients,然后面试老爷 ...

  5. 可拖拽dialog

    指令的封装转自https://blog.csdn.net/sinat_21902709/article/details/86545444 可拖拽dialog应用于很多弹出框,所以需要作用于全局 在插件 ...

  6. 【洛谷 P5017】 摆渡车(斜率优化)

    题目链接 算是巩固了一下斜率优化吧. 设\(f[i]\)表示前\(i\)分钟最少等待时间. 则有\(f[i]=\min_{j=0}^{i-m}f[j]+(cnt[i]-cnt[j])*i-(sum[i ...

  7. 【洛谷 P3346】 [ZJOI2015]诸神眷顾的幻想乡(后缀自动机)

    题目链接 广义sam+不同子串个数.. 找到所有入度为\(0\)的点开始\(dfs\),建出广义sam. 然后就是不同子串个数了 #include <cstdio> #include &l ...

  8. 数据结构与算法(周测7-拓扑排序和AOV网络)

    判断题 1.AOE图的关键路径就是最长的路径      T      F 2.AOE图的权值最大的边(活动)一定是关键活动.      T      F 两条边相加可能比最大的边还要大. 3.在AOE ...

  9. 大数据相关技术原理资料整理(hdfs, spark, hbase, kafka, zookeeper, redis, hive, flink, k8s, OpenTSDB, InfluxDB, yarn)

    hdfs: hdfs官方文档 深入理解HDFS的架构和原理 https://blog.csdn.net/kezhong_wxl/article/details/76573901 HDFS原理解析(总体 ...

  10. trie树(前缀树)详解——PHP代码实现

    trie树常用于搜索提示.如当输入一个网址,可以自动搜索出可能的选择.当没有完全匹配的搜索结果,可以返回前缀最相似的可能. 一.Tire树的基本性质 根节点不包含字符,除根节点外每一个节点都只包含一个 ...