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

The idea is to add a set to the hashMap to remember all the locations of a duplicated number.

 public class RandomizedCollection {
HashMap<Integer, HashSet<Integer>> map;
ArrayList<Integer> arr;
java.util.Random random; /** Initialize your data structure here. */
public RandomizedCollection() {
map = new HashMap<Integer, HashSet<Integer>>();
arr = new ArrayList<Integer>();
random = new java.util.Random();
} /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
public boolean insert(int val) {
boolean res = false;
if (!map.containsKey(val)) {
map.put(val, new HashSet<Integer>());
res = true;
}
arr.add(val);
map.get(val).add(arr.size()-1);
return res;
} /** Removes a value from the collection. Returns true if the collection contained the specified element. */
public boolean remove(int val) {
if (!map.containsKey(val)) return false;
int lastItem = arr.get(arr.size()-1);
int index = arr.size()-1;
if (lastItem != val) {
HashSet<Integer> lastItemSet = map.get(lastItem);
index = map.get(val).iterator().next();
arr.set(index, lastItem);
lastItemSet.remove(arr.size()-1);
lastItemSet.add(index);
} if (map.get(val).size() == 1) map.remove(val);
else map.get(val).remove(index);
arr.remove(arr.size()-1);
return true;
} /** Get a random element from the collection. */
public int getRandom() {
return arr.get(random.nextInt(arr.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();
*/

Leetcode: Insert Delete GetRandom O(1) - Duplicates allowed的更多相关文章

  1. [LeetCode] Insert Delete GetRandom O(1) - Duplicates allowed 常数时间内插入删除和获得随机数 - 允许重复

    Design a data structure that supports all following operations in average O(1) time. Note: Duplicate ...

  2. 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). ...

  3. 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 常数时间内插入删除和获得随机数 - 允许重复

    Design a data structure that supports all following operations in average O(1) time. Note: Duplicate ...

  5. [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 ...

  6. LeetCode 381. Insert Delete GetRandom O(1) - Duplicates allowed

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

  7. 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 ...

  8. 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 ...

  9. [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 ...

随机推荐

  1. struct stat结构体的详解和用法

    [cpp] view plaincopy //! 需要包含de头文件 #include <sys/types.h> #include <sys/stat.h> S_ISLNK( ...

  2. nrf51822-广播模式

    解决以下几个问题: 1 SDK9 中的几种广播模型 2 广播超时如何进入睡眠 3 如何取消广播超时睡眠使其可以无限广播. 1 SDK9 中的几种广播模型 Nordci SDK对于广播方面有一个模块.这 ...

  3. Mongo对内嵌文档的CRUD

    { "_id" : ObjectId("5706032acd0a6194868cf53e"), "list" : { "age&q ...

  4. Dom方式解析XML

    public class TestXML { public static void main(String[] args) throws SAXException, IOException { //D ...

  5. Makefile使用总结

    1. Makefile 简介 Makefile 是和 make 命令一起配合使用的. 很多大型项目的编译都是通过 Makefile 来组织的, 如果没有 Makefile, 那很多项目中各种库和代码之 ...

  6. git push错误解决方案

    错误提示: error: The requested URL returned error: 403 Forbidden while accessing https://nanfei9330@gith ...

  7. Html / CSS常见问题 解决方案

    解决Safari下input光标过大 input { line-height: normal; } 设置浮层 html, body { /*只有父元素设置宽高为100%子元素设置宽高100%时才能撑满 ...

  8. C# 时间与时间戳互转 13位

    /// <summary> /// 将c# DateTime时间格式转换为Unix时间戳格式 /// </summary> /// <param name="t ...

  9. 实验 snort安装配置与规则编写

    1 实验目的 在linux或windows任意一个平台下完成snort的安装,使snort工作在NIDS模式下,并编写符合相关情景要求的snort规则. 2 实验环境 物理机:windows 8.1 ...

  10. 免费真机调试 -- Xcode7以上版本

    刚新安装了Xcode7 , 据说这个版本可以免费真机调试,于是用了一个新的AppID测试了,发现真的可以免费真机调试了呢!新的appId账号(随便一个苹果手机账号就行),没有支付每年的99美刀,也没有 ...