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. jQuery之换肤与cookie插件

    有时候一个网页可以有多个皮肤进行选择,也就是不同的背景,或是一整套新的css,能使整个页面变成另一种风格. 这个功能可以用jQuery来实现.外加cookie插件.有了cookie,就可以长时间的保存 ...

  2. page show

    controller public function record() { $r = ; $m = M(); $query = $m->query('select count(1) as cou ...

  3. DML以及DQL的使用方法

    DML:数据操作语言 1.插入insert into 单行插入:insert into 表名 (字段名, 字段名,...) values (值, 值, ...) 注:值列表要和字段列表相匹配. ins ...

  4. ②springMVC入门

    1 1.1      需求 以案例作为驱动. springmvc和mybaits使用一个案例(商品订单管理). 功能需求:商品列表查询 1.2      环境准备 数据库环境:mysql5.1

  5. SQL实现将一个表的数据插入到另外一个表的代码

    --第一种情况的 1>如果2张表的字段一致,并且希望插入全部数据,可以用这种方法: INSERT INTO 目标表 SELECT * FROM 来源表; 2>比如要将 articles 表 ...

  6. Redis学习笔记(6)-SortedSet

    package cn.com; import java.util.HashMap; import java.util.Map; import java.util.Set; import redis.c ...

  7. Qt 之 使用 https发送 HTTP请求(使用OPENSSL库)

    一.简述 在使用Qt发送HTTP请求中一般使用的链接都是http://前缀,而有的服务器支持 https://前缀的链接,而Qt本身是支持https的,但是https访问需要用到SSL认证,而QT默认 ...

  8. C++控制程序只运行一个实例

    int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { ...

  9. JQuery通过$(xxx...)返回对象

    var JQ = function () { return new JQ.prototype.init(); }; JQ.prototype.init = function () { }; JQ.pr ...

  10. angularJS平行控制器间共享数据

    <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8&quo ...