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. s3express截图安装教程

    1.安装s3express_setup.exe 2.设置s3express 设置服务器地址setopt -endpoint:s3.cn-north-1.amazonaws.com.cn 设置协议set ...

  2. PHP下载文件的几种方案

    PHP下载远程文件的3种方法以及性能考虑 2014-02-21      0个评论       收藏    我要投稿 今天在做导出Excel的时候,总是要测试导出的Excel文件,频繁的下载和打开,很 ...

  3. 最小化Linux系统安装

    安装CentOS 5.9 基于vbox虚拟机,虚拟机内存1 G,虚拟硬盘大小8 G 虚拟网卡使用host only方式 创建卷组centos 独立的boot分区 home, root和swap分区皆是 ...

  4. MIT提出精细到头发丝的语义分割技术,打造效果惊艳的特效电影

    来自 MIT CSAIL 的研究人员开发了一种精细程度远超传统语义分割方法的「语义软分割」技术,连头发都能清晰地在分割掩码中呈现.在对比实验中,他们的结果远远优于 PSPNet.Mask R-CNN. ...

  5. Linux内存管理大图(第三稿)

    http://bbs.chinaunix.net/thread-2018659-2-1.html 描述讨论在http://bbs.chinaunix.net/thread-3760371-1-1.ht ...

  6. 让“懒惰” Linux 运维工程师事半功倍的 10 个关键技巧!

    好的Linux运维工程师区分在效率上.如果一位高效的Linux运维工程师能在 10 分钟内完成一件他人需要 2 个小时才能完成的任务,那么他应该受到奖励(得到更多报酬),因为他为公司节约了时间,而时间 ...

  7. python json.loads json.dumps(ensure_ascii = False) 汉字乱码问题解决

    python 转换为json时候 汉字编码问题 2017年03月23日 18:50:04 阅读数:5604 有这样一个需求: 需要一个json 文件 数据从数据库里查询出来 1. 设置文件头 # -* ...

  8. canvas学习笔记、小函数整理

    http://bbs.csdn.net/topics/391493648 canvas实例分享 2016-3-16 http://bbs.csdn.net/topics/390582151 html5 ...

  9. setlocal 与 变量延迟

    setlocal 与 变量延迟 本条内容引用[英雄出品]的批处理教程: 要想进阶,变量延迟是必过的一关!所以这一部分希望你能认真看. 为了更好的说明问题,我们先引入一个例子.例1: @echo off ...

  10. overflow: auto 图片自适应调整

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