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. Rochester Memory Hardware Error Research Project

    http://www.cs.rochester.edu/research/os/memerror/

  2. Java中方法的覆写

    所谓方法的覆写override就是子类定义了与父类中同名的方法,但是在方法覆写时必须考虑权限,即被子类覆写的方法不能拥有比父类方法更加严格的访问权限. 修饰符分别为public.protected.d ...

  3. python环境搭建

    Python下载 Python最新源码,二进制文档,新闻资讯等可以在Python的官网查看到: Python官网:http://www.python.org/ 你可以在一下链接中下载Python的文档 ...

  4. [ASP.NET] Dictionary 和 Hashtable 区别

    Dictionary和Hashtable 是两个比较常用的表示键/值的集合,两者在实际使用过程中有何区别呢? 具体区别如下: 1. Hashtable不支持泛型,而Dictionary支持泛型. 2. ...

  5. npm的使用

    npm的用途: 用官方的包 用其他人的包 传自己的包给别人用 一: 安装 1.用别人的: npm install argv 这样下载好之后,argv包就放在了工程目录下的node_modules目录中 ...

  6. start from here

    简单介绍下,小码农一只,工作两年左右,从事移动端游戏开发工作. 人类,精神正常,男,爱好游戏音乐足球美女,if(有妹子) 喜欢旅游;,取向正常. 很喜欢java,喜欢关注新技术, 应一些朋友的建议,今 ...

  7. 利用ArcMap对tiff或jpg格式地图图片的配准步骤

    原文:利用ArcMap对tiff或jpg格式地图图片的配准步骤 在实际应用中,经常会遇到提供一张高精度的地图图片文件,如何对将该图片进行配准(使图片具有经纬度坐标). 当然我们得有一些大概的参考图层, ...

  8. QQ聊天气泡(图片拉伸不变样)、内容尺寸定制(高度随字数、字体而变)

    - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; /** QQ聊 ...

  9. 常用 linux 命令(部分)

    常用命令总结: 1. mkdir命令 mkdir dirname , 用来创建目录.该命令创建由dirname命名的目录.如果在目录名的前面没有加任何路径名,则在当前目录下创建由dirname指定的目 ...

  10. [转]Android 延迟执行

    开启新线程 new Thread(new Runnable(){ public void run(){ Thread.sleep(XXXX); handler.sendMessage(); //告诉主 ...