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. Java多态性理解

      Java中多态性的实现 什么是多态 面向对象的三大特性:封装.继承.多态.从一定角度来看,封装和继承几乎都是为多态而准备的.这是我们最后一个概念,也是最重要的知识点. 多态的定义:指允许不同类的对 ...

  2. your project contains error(s),please fix them before running your application.错误总结

             Android开发中的问题总是多种多样,今天我来总结一个浪费了我一个晚上的错误T-T:your project contains error(s),please fix them b ...

  3. 取url的键值对,location的search:从?开始的字符串

    function urlArgs(){ var args=""; var query=location.search.substring(1);//去除问号 var pairs=q ...

  4. PHP其它常用函数;<<<面向对象(OPP)的三大特性:封装、继承、加态:>>> <----面试题 ;构造方法、析构方法,魔术方法、set、get方法;静态;抽象类;接口

    PHP其它常用函数:     赋值:$r->name = "元素";      取值: echo $r->name;  count()   计算数组中的元素数目或对象中 ...

  5. ava.lang.NullPointerException的一般解决方法

    抛出异常后,一般会输出异常信息,, 从上往下找 ,第一次出现与"自己的代码"有关的部分,就是异常抛出的最近点,异常就是在那里开始的 然后再顺藤摸瓜 找问题去吧

  6. docker rabbitmq

    docker run -d --hostname my1 --name dome-rabbit -p 15673:5672 -p 15674:15672 -e RABBITMQ_ERLANG_COOK ...

  7. 大数据下的java client连接JDBC

    1.前提 启动hiveserver2服务 url,username,password 2.程序 3.结果 emp的第一列与第二列

  8. EF6 CodeFirst 启用Migration,常用命令

    Enable-Migrations –EnableAutomaticMigrationsAdd-Migration [MigrationName] [-Force]Update-Database –T ...

  9. 设计模式:中介者模式(Mediator)

    定   义:用一个中介对象来封装一系列对象的交互.中介者使各个对象不需要显示地相互作用,从而耦合松散,而且可以独立的改变他们之间的交互. 结构图: Mediator类,抽象中介者类 abstract ...

  10. Spring冲刺阶段二(1)

    我们首先是根据同学们的评价来找补自己的不足之处,其中同学们反应最多的是我们的界面不够好看,但是我觉得虽然不好看但算是比较简洁.其次是没有体现内网在其中发挥的作用,这点我们还没有实现. 根据这些不足之处 ...