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

题目标签:Array, Hash Table, Design
  这道题目基于#380 的情况下,可以允许有重复项。回顾一下380, 因为要达到 insert, remove 和 getRandom 都是O(1) 的时间,我们需要ArrayList 来保存所有的数字,利用map 来保存 数字 和 index 之间的映射。
  这道题目允许了重复项,那么在map 里 key 是数字, value 是index, 这里的index 就会不止一个了。我们要把所有重复的数字的 index 也保存进来, 所以把 map 里value 改成 HashSet 来保存所有的index。
 
  insert val:如果map里没有val,需要新建一个HashSet,并且加入nums (ArrayList);
         如果有val,直接加入新的index 进HashSet,并且加入nums (ArrayList);  
        
  remove val:如果val 在nums 里是最后一个的话,只需要在map 里删除val 的index, 并且在nums 里删除最后一个数字。
        如果val 在nums 里不是最后一个的话,需要额外的把 nums 里最后一个数字的值 复制到 val, 删除val 在map里的 index,还要把最后一个数字的index 在map 里更新,并且在nums 里删除最后一个数字。
 
  其他基本都和#380 差不多,具体看code。
 

Java Solution:

Runtime beats 88.45%

完成日期:09/18/2017

关键词:Array, Hash Table, Design

关键点:利用array 保存数值;利用map<Integer, HashSet<>>保存 - 数值 当作key,数值在array里的所有index 保存在HashSet,当作value。

 class RandomizedCollection
{
private HashMap<Integer, HashSet<Integer>> map; // key is value, value is index HashSet
private ArrayList<Integer> nums; // store all vals
private java.util.Random rand = new java.util.Random(); /** Initialize your data structure here. */
public RandomizedCollection()
{
map = new HashMap<>();
nums = new ArrayList<>();
} /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
public boolean insert(int val)
{
boolean contain = map.containsKey(val); // if map doesn't have val, meaning map doesn't have HashSet
if(!contain)
map.put(val, new HashSet<Integer>()); // create HashSet // add index into HashSet
map.get(val).add(nums.size());
nums.add(val); return !contain; // if collection has val, return false; else return true
} /** Removes a value from the collection. Returns true if the collection contained the specified element. */
public boolean remove(int val)
{
boolean contain = map.containsKey(val);
if(!contain)
return false;
// get an index from HashSet of Map
int valIndex = map.get(val).iterator().next();
map.get(val).remove(valIndex); // remove this index from val's set if(valIndex != nums.size() - 1) // if this val is not the last one in nums
{
// copy the last one value into this val's position
int lastNum = nums.get(nums.size() - 1);
nums.set(valIndex, lastNum);
// update the lastNum index in HashSet
map.get(lastNum).remove(nums.size() - 1); // remove the last number's index from set
map.get(lastNum).add(valIndex); // add new index into set
} if(map.get(val).isEmpty()) // if val's set is empty
map.remove(val); // remove val from map nums.remove(nums.size() - 1); // only remove last one O(1) return true;
} /** Get a random element from the collection. */
public int getRandom()
{
return nums.get(rand.nextInt(nums.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();
*/

参考资料:

https://discuss.leetcode.com/topic/53216/java-solution-using-a-hashmap-and-an-arraylist-along-with-a-follow-up-131-ms/5

LeetCode 题目列表 - LeetCode Questions List
 

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

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

  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. Core Java 简单谈谈HashSet

    同学们在看这个问题的时候,我先提出者两个问题,然后大家带着问题看这个文章会理解的更好. HashSet为什么添加元素时不能添加重复元素? HashSet是否添加null元素? 打开源码, 我们看到如下 ...

  2. python数据分析panda库

    panda内有两种数据结构,Series()和DataFrame() >>> a=pd.Series([1,2],index=['a','b']) >>> a a ...

  3. Spring第四篇【Intellij idea环境下、Struts2和Spring整合】

    前言 Spring的第二和第三篇已经讲解了Spring的基本要点了[也就是Core模块]-本博文主要讲解Spring怎么与Struts2框架整合- Struts2和Spring的整合关键点: acti ...

  4. log4j 日志脱敏处理 + java properties文件加载

    Java 加载Properties 配置文件: ResourceBundle bundle = ResourceBundle.getBundle("log4j_filter"); ...

  5. Linux环境下启动MySQL数据库出现找不到mysqld.sock的解决办法!

    问题: 在普通用户权限下运行:mysql -u root -p,回车之后如果会出现如下错误:ERROR 2002 (HY000): Can't connect to local MySQL serve ...

  6. git记录用户名

    windows下比较比较好用的Git客户端有2种: 1. msysgit + TortoiseGit(乌龟git) 2. GitHub for Windows github的windows版也用过一段 ...

  7. 基于 Electron 的爬虫框架 Nightmare

    作者:William 本文为原创文章,转载请注明作者及出处 Electron 可以让你使用纯 JavaScript 调用 Chrome 丰富的原生的接口来创造桌面应用.你可以把它看作一个专注于桌面应用 ...

  8. asp.net core封装layui组件示例分享

    用什么封装?自然是TagHelper啊,是啥?自己瞅文档去 在学习使用TagHelper的时候,最希望的就是能有个Demo能够让自己作为参考 怎么去封装一个组件? 不同的情况怎么去实现? 有没有更好更 ...

  9. node-Telnet

    什么是Telnet(window系统) 使用Telnet工具作为客户端对创建的TCP服务器进行会话交流时遇到的问题做一个简单的记录.希望可以帮助到一些同学. 这里看一下百度词条的解释 Telnet协议 ...

  10. CentOS7 + Nginx1.13.5 + PHP7.1.10 + MySQL5.7.19 源码编译安装

    一.安装Nginx 1.安装依赖扩展 # yum -y install wget openssl* gcc gcc-c++ autoconf libjpeg libjpeg-devel libpng ...