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 ...
随机推荐
- Java、javax、org、sun、Java.util等常用包的区别、详解、实例
Java.javax.org.sun包都是jdk提供的类包,且都是在rt.jar中.rt.jar是JAVA基础类库(java核心框架中很重要的包),包含lang在内的大部分功能,而且rt.jar默认就 ...
- 多线程面试题系列(3):原子操作 Interlocked系列函数
上一篇中讲到一个多线程报数功能.为了描述方便和代码简洁起见,我们可以只输出最后的报数结果来观察程序是否运行出错.这也非常类似于统计一个网站每天有多少用户登录,每个用户登录用一个线程模拟,线程运行时会将 ...
- Bootstrap栅格系统用法--Bootstrap基础
1.栅格系统实现布局的原理 1)Bootstrap把屏幕的宽度拆分成12格(列),每一格像素的多少由设备屏幕分辨率决定,我们在开发项目的过程中不需要去指定像素或者百分比. 2)不同范围的分辨率对应不同 ...
- CSS3 3D环境实现立体 魔方效果代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- 【转】SWT/JFace的对话框
一.MessageDialog ,MessageDialog的用法很简单 MessageDialog.openInfomation(shell,title,message); ...
- 【轉】使用jQuery播放/暂停 HTML5视频
jQuery不可以使用play()方法,但js是可以的: document.getElementById('movie1').play(); 解决方法:play并不是jQuery的函数,而是DOM ...
- MySQL基本语法(一):和SQL Server语法的差异小归纳
html { font-family: sans-serif } body { margin: 0 } article,aside,details,figcaption,figure,footer,h ...
- 回文词_KEY
回文词 (palin.pas/c/cpp) [问题描述] 回文词是一种对称的字符串--也就是说,一个回文词,从左到右读和从右到左读得的结果是一样的.任意给定一个字符串,通过插入若干字符,都可以变成一个 ...
- 多线程简单实例(1)真的需要synchronized么?
说道多线程的安全问题,很多人想到就就是加锁.用到synchronized关键字. 那就要先说说synchronized问什么能够保证线程安全了. 首先要了解线程的工作方式:线程工作分为工作内存和主内存 ...
- ASP.NET Core 认证与授权[2]:Cookie认证
由于HTTP协议是无状态的,但对于认证来说,必然要通过一种机制来保存用户状态,而最常用,也最简单的就是Cookie了,它由浏览器自动保存并在发送请求时自动附加到请求头中.尽管在现代Web应用中,Coo ...