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 ...
随机推荐
- PowerBI开发 第四篇:DAX表达式
DAX 表达式主要用于创建度量列(Measure),度量值是根据用户选择的Filter和公式,计算聚合值,DAX表达式基本上都是引用对应的函数,函数的执行有表级(Table-Level)上下文和行级( ...
- python 实现文本文件中的数字按序排序(位操作,低内存占用)
文本文件内容 ./txt 3241155299893344 处理代码: import sys a = bytearray(b'') for i in range(100): a.append(or ...
- vue 2 使用Bus.js进行兄弟(非父子)组件通信 简单案例
vue2中废弃了$dispatch和$broadcast广播和分发事件的方法.父子组件中可以用props和$emit().如何实现非父子组件间的通信,可以通过实例一个vue实例Bus作为媒介,要相互通 ...
- 详解 HTTPS 移动端对称加密套件优
近几年,Google.Baidu.Facebook 等互联网巨头大力推行 HTTPS,国内外的大型互联网公司很多也都已启用全站 HTTPS. Google 也推出了针对移动端优化的新型加密套件 Cha ...
- QT的安装及环境配置
QT的安装及环境配置 一.windows的下QT的安装及环境配置 (一)从框架安装程序中安装 步骤: 准备:下载QT库,下载指定版本的MINGW,QT IDE 1.下载QT安装文件如:qt-win-o ...
- 如何使用git 发布源码到CodePlex
github 是分布式源码管理系统 codeplex 是微软的开源社区 将git中源码分享到codeplex社区其实很方便,按照如下步骤: 1:注册codeplex 帐号或使用微软的已有的帐号 2:下 ...
- apollo实现c#与android消息推送(四)
4 Android代码只是为了实现功能,比较简单,就只是贴出来 package com.myapps.mqtttest; import java.util.concurrent.Executors; ...
- HDU 5974 数学
A Simple Math Problem Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Ot ...
- Operating system hdu 2835 OPT
Operating system Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) ...
- SGU180(树状数组,逆序对,离散)
Inversions time limit per test: 0.25 sec. memory limit per test: 4096 KB input: standard output: sta ...