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 ...
随机推荐
- 在windows下安装flex和bison
学习Stellar-core 需要依赖项flex .bison .gcc三个依赖项 下载得网址:链接: https://pan.baidu.com/s/1mitCLcs 密码: 3jaj 通过 w ...
- java.lang.RuntimeException: java.sql.SQLException: Too many parameters: expected 0, was given 1 Quer
如果出现类似这样的错误,检查一下是否sql语句和参数的位置对调了. java.lang.RuntimeException: java.sql.SQLException: Too many parame ...
- Spring 级联属性
Spring 级联属性是当两个bean 关联时 从一个bean 给 另一个bean 赋值 Application xml 配置如下 <bean id="ZhangSan" ...
- 循环语句for,while,until,select
循环 *循环执行 将某代码段重复运行多次 重复运行多少次: 循环次数事先已知 循环次数事先未知 有进入条件和退出条件 *常见的循环语句有for,while,until for循环 for 变量名 n ...
- Linux入门之常用命令(12) mount
查看Linux所有设备 cd /dev ls -l sd* //分区 查看Linux磁盘 fdisk -lu 挂载 一般挂载至/mnt /media mount /dev/sda5 /mnt/ ...
- 翻译:MLAPP(2.2节 概率论简要回顾)
笔者:尝试翻译MLAPP(Machine Learning: a Probabilistic Perspective)一书,供机器学习的学者参考,如有错误理解之处请指出,不胜感激!(如需转载,请联系本 ...
- LeetCode 650 - 2 Keys Keyboard
LeetCode 第650题 Initially on a notepad only one character 'A' is present. You can perform two operati ...
- NOIP2014_day2:无线网络发射器选址
#include<stdio.h>//NOIP2014 day2 :无线网络发射器选址 ,max=; ][]; void wifi(int a,int b,int c) { int i,j ...
- MySQL Windows版安装详解
一.下载MySQL MySQL官网https://dev.mysql.com提供了Windows下的安装版msi和解压版zip,其中均包含32和64位版本,mis版本与SqlServer安装基本一致N ...
- 学习如何看懂SQL Server执行计划(一)——数据查询篇
一.数据查询部分 1. 看到执行计划有两种方式,对sql语句按Ctrl+L,或按Ctrl+M打开显示执行计划窗口每次执行sql都会显示出相应的执行计划 2. 执行计划的图表是从右向左看的 3. SQL ...