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 elements are allowed.
insert(val)
: Inserts an item val to the collection.remove(val)
: Removes an item val from the collection if present.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();
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 381. Insert Delete GetRandom O(1) - Duplicates allowed (插入删除和获得随机数 常数时间 允许重复项)的更多相关文章
- [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 ...
- 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 ...
- [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 ...
- LeetCode 381. Insert Delete GetRandom O(1) - Duplicates allowed
原题链接在这里:https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/?tab=Description ...
- [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 ...
- 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). ...
- 381. Insert Delete GetRandom O(1) - Duplicates allowed
Design a data structure that supports all following operations in average O(1) time. Note: Duplicate ...
- 381 Insert Delete GetRandom O(1) - Duplicates allowed O(1) 时间插入、删除和获取随机元素 - 允许重复
设计一个支持在平均 时间复杂度 O(1) 下, 执行以下操作的数据结构.注意: 允许出现重复元素. insert(val):向集合中插入元素 val. remove(val):当 val ...
- 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 ...
随机推荐
- PKI信息安全知识点详细解答包含HTTPS
1. 什么是X.509? X.509标准是ITU-T设计的PKI标准,他是为了解决X.500目录中的身份鉴别和访问控制问题设计的. 2. 数字证书 数字证书的意义在于回答公钥属于谁的问题,以帮助用户安 ...
- cityEngine入门(实现数据的预处理以及cityEngine的3维显示)
一. 实验要求 1. 提供数据: 中田村两个图幅影像数据 DEM提供包含高程数值的文本和矢量数数据 完成内容: 实现中田村两个图幅的拼接,生成一个影像数据(Image.tif) 将DEM数据 ...
- 用List传递学生信息
集合在程序开发中经常用到,例如,在业务方法中将学生信息.商品信息等存储到集合中,然后作为方法的返回值返回给调用者,以此传递大量的有序数据. 本实例将使用List集合在方法之间传递学生的信息.实例效果如 ...
- 编程从入门到提高,然后放弃再跑路(Java)
1.Java入门篇 1.1 基础入门和面向对象 1.1.1 编程基础 [01] Java语言的基本认识 [02] 类和对象 [03] 类的结构和创建对象 [04] 包和访问权限修饰符 [05] 利用p ...
- 浅谈SQL优化入门:2、等值连接和EXPLAIN(MySQL)
1.等值连接:显性连接和隐性连接 在<MySQL必知必会>中对于等值连接有提到两种方式,第一种是直接在WHERE子句中规定如何关联即可,那么第二种则是使用INNER JOIN关键字.如下例 ...
- 高德地图markers生成和点击
因为自己平时上班也是比较忙,遇到什么写什么,希望能给现在的你一些帮助,都是自己在工作中遇到的问题,给自己一个提醒,也是分享 相信很多人在做高德地图开发的时候,对于新手,官方的demo解读单个marke ...
- 异常处理第一讲(SEH),筛选器异常,以及__asm的扩展,寄存器注入简介
异常处理第一讲(SSH),筛选器异常,以及__asm的扩展 博客园IBinary原创 博客连接:http://www.cnblogs.com/iBinary/ 转载请注明出处,谢谢 一丶__Asm的 ...
- Axios源码阅读笔记#1 默认配置项
Promise based HTTP client for the browser and node.js 这是 Axios 的定义,Axios 是基于 Promise,用于HTTP客户端--浏览器和 ...
- SimpleRpc-序列化与反序列化的设计与实现
为什么需要序列化和反序列化? 假设你是客户端,现在要调用远程的加法计算服务,你与服务端商定好了发送数据的格式:发送8个字节的请求,前4字节是第一个数,后4字节是第二个数,服务端读取数据的时候也按照商定 ...
- Java学习笔记一---JVM、JRE、JDK
jdk包含jre,jre包含jvm. 用java语言进行开发时,必须先装jdk: 只运行java程序,不进行开发时,可以只装jre. JVM 即Java Virtual machine,Java虚拟机 ...