原题链接在这里: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. Linux系统下Redis单机版的安装详细教程

    Linux系统下Redis单机版的安装详细教程 1.下载软件安装包并上传到root目录 这里以旧版本的3.0进行安装,比较成熟稳定,具体软件可以通过qq群534073451文件下载

  2. lmir 随笔

    近期需要研究一些特征工程的工作,就打算把微软之前公布出来的特征都复现一遍,今天遇到的特征是 LMIR, 其实也就是language model for information retrieval的简写 ...

  3. 使用PHP开发HR系统(6)

        本节讲述如何连接Postgre数据库并查询与显示数据. ==================================================================== ...

  4. iOS核心动画(基础篇)

    Core Animation相关内容基本介绍 此框架把屏幕上的内容组合起来,这个内容被分解成图层,放到图层树中,这个树形成了你能在应用程序看到的内容的基础 图层在iOS中就是CALayer类 当我们创 ...

  5. SpringCloudConfig相关配置简介、使用、整合Eureka

    目的: 1.SpringCloud Config简介 2.Config Server基本使用 3.Config Client基本使用 4.Config整合Eureka 5.Config配置搜索路径 S ...

  6. vue+ElementUI+高德API地址模糊搜索(自定义UI组件)

    开发环境描述: Vue.js ElementUI 高德地图API 需求描述: 在新增地址信息的时候,我们需要根据input输入的关键字调用地图的输入提示API,获取到返回的数据,并根据这些数据生成下拉 ...

  7. VsCode使用setting sync 同步自己的插件和设置等

    直接再 Vscode中安装就可以,然后: 1. 可以点看setting sync插件在vscode 这个时候可以按照提示进行设置(也可以参考下:https://www.cnblogs.com/kenz ...

  8. SpringBoot学习之@Configuration注解和@Bean注解

    @Configuration 1.@Configuration注解底层是含有@Component ,所以@Configuration 具有和 @Component 的作用. 2.@Configurat ...

  9. c# 表达式目录树拷贝对象(根据对象类型动态生成表达式目录树)

    表达式目录树,在C#中用Expression标识,这里就不介绍表达式目录树是什么了,有兴趣可以自行百度搜索,网上资料还是很多的. 这里主要分享的是如何动态构建表达式目录树. 构建表达式目录树的代码挺简 ...

  10. Charles中文破解版下载安装及使用教程(附带免费下载链接)

    一. 简介及安装 Charles 是在 PC 端常用的网络封包截取工具,但它不仅仅能在pc端使用,还可以在手机ios和安卓端都可以使用.我们在做移动开发或者测试网页app时候,为了调试与服务器端的网络 ...