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

Note: Duplicate elements are allowed.

  1. insert(val): Inserts an item val to the collection.
  2. remove(val): Removes an item val from the collection if present.
  3. 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();

Solution1: HashMap + ArrayList

code

 public class RandomizedCollection {
class Node {
public int value;
public int index;
public Node(int val, int idx) {
value = val;
index = idx;
}
} private Map<Integer, List<Integer>> map;
private List<Node> list;
private Random r; /** Initialize your data structure here. */
public RandomizedCollection() {
map = new HashMap<>();
list = new ArrayList<>();
r = new Random();
} /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
public boolean insert(int val) {
List<Integer> l = map.getOrDefault(val, new ArrayList<>());
l.add(list.size());
map.put(val, l);
list.add(new Node(val, l.size() - 1));
return l.size() == 1;
} /** 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;
List<Integer> l = map.get(val);
int removeIdx = l.get(l.size() - 1);
Node replaceNode = list.get(list.size() - 1); // deal with HashMap
map.get(replaceNode.value).set(replaceNode.index, removeIdx);
l.remove(l.size() - 1);
if (l.size() == 0) map.remove(val); // deal with List
list.set(removeIdx, replaceNode);
list.remove(list.size() - 1); return true;
} /** Get a random element from the collection. */
public int getRandom() {
return list.get(r.nextInt(list.size())).value;
}
}

[leetcode]381. Insert Delete GetRandom O(1) - Duplicates allowed常数时间插入删除取随机值的更多相关文章

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

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

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

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

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

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

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

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

  7. [leetcode]380. Insert Delete GetRandom O(1)常数时间插入删除取随机值

    Design a data structure that supports all following operations in average O(1) time. insert(val): In ...

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

  9. 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. (转)Win7 64位系统下 Retional rose 2003 安装及破解

    网上关于Retional rose 2003安装和破解的文章比较多,这里,我结合自己的亲身体验,和大家分享一下win7 旗舰版 64位系统下Retional rose 2003(下面简称rose200 ...

  2. [UE4]Visual Studio的相关插件安装:UE4.natvis和UnrealVS Extension

    转自:http://aigo.iteye.com/blog/2281182 UE4.natvis 官方文档: https://docs.unrealengine.com/latest/INT/Prog ...

  3. 最简单的TCP、UDP案例及各函数的详细解释

    TCP: server #include "stdafx.h" #include<iostream> #define BUF_SZIE 64 #include &quo ...

  4. 知乎日报 API的图片盗链问题

    由最近 基于vue的知乎日报单页应用 引发的问题 以及问题解决历程 通过 知乎日报API 基于vue做一个知乎日报的单页应用,在获取图片时存在一个图片盗链问题,图片无法加载 提示 403 错误, 最终 ...

  5. oracle使用随笔

    一,centos 7安装桌面环境 首先使用命令yum grouplist查看可以使用的group ,第一步,命令安装Gnome Desktop,第二步,yum groupinstall "X ...

  6. zabbixzabbix

    一,安装文档    https://www.zabbix.com/documentation/4.0/zh/manual/installation/requirements zabbix3.2.6安装 ...

  7. 28. 表单css样式定义格式

    form>table>tbody>tr>td{padding:5px;font-size:14px;font-family:"Microsoft YaHei" ...

  8. Spring Boot实践——用外部配置填充Bean属性的几种方法

    引用:https://blog.csdn.net/qq_17586821/article/details/79802320 spring boot允许我们把配置信息外部化.由此,我们就可以在不同的环境 ...

  9. Kotlin语言学习笔记(5)

    委托模式(Delegation) 类的委托 interface Base { fun print() } class BaseImpl(val x: Int) : Base { override fu ...

  10. Haskell语言学习笔记(26)Identity, IdentityT

    Identity Monad newtype Identity a = Identity { runIdentity :: a } instance Functor Identity where fm ...