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

题目:

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();

题解:

用set来保存val的所有index.

Time Complexity: insert, O(1). remove, O(1). getRandom, O(1).

Space: O(n).

AC Java:

 class RandomizedCollection {
ArrayList<Integer> list;
HashMap<Integer, LinkedHashSet<Integer>> numToInds; /** Initialize your data structure here. */
public RandomizedCollection() {
list = new ArrayList<>();
numToInds = new HashMap<>();
} /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
public boolean insert(int val) {
boolean contains = numToInds.containsKey(val);
if(!contains){
numToInds.put(val, new LinkedHashSet<Integer>());
} numToInds.get(val).add(list.size());
list.add(val);
return contains;
} /** Removes a value from the collection. Returns true if the collection contained the specified element. */
public boolean remove(int val) {
if(!numToInds.containsKey(val) || numToInds.get(val).size() == 0){
return false;
} LinkedHashSet<Integer> lhs = numToInds.get(val);
int ind = lhs.iterator().next();
lhs.remove(ind);
int last = list.get(list.size() - 1);
list.set(ind, last);
numToInds.get(last).add(ind);
numToInds.get(last).remove(list.size() - 1);
list.remove(list.size() - 1);
return true;
} /** Get a random element from the collection. */
public int getRandom() {
Random rand = new Random();
return list.get(rand.nextInt(list.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();
*/

类似Insert Delete GetRandom O(1).

LeetCode 381. Insert Delete GetRandom O(1) - Duplicates allowed的更多相关文章

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

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

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

  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常数时间插入删除取随机值

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

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

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

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

  8. 381 Insert Delete GetRandom O(1) - Duplicates allowed O(1) 时间插入、删除和获取随机元素 - 允许重复

    设计一个支持在平均 时间复杂度 O(1) 下, 执行以下操作的数据结构.注意: 允许出现重复元素.    insert(val):向集合中插入元素 val.    remove(val):当 val ...

  9. 381. Insert Delete GetRandom O(1) - Duplicates allowed允许重复的设计1数据结构

    [抄题]: Design a data structure that supports all following operations in average O(1) time. Note: Dup ...

随机推荐

  1. Nmap脚本使用

    Nmap是主机扫描工具,他的图形化界面是Zenmap,分布式框架为Dnamp. Nmap可以完成以下任务: 主机探测 端口扫描 版本检测 系统检测 支持探测脚本的编写 Nmap在实际中应用场合如下: ...

  2. Java -- 最简单的认识重载

    定义 方法的名称相同,参数个数或类型不同的时候就成为方法重载. 示例 编写一个两个数相加的方法: public class hello{ public static void main(String ...

  3. 深度自适应增量学习(Incremental Learning Through Deep Adaptation)

    深度自适应增量学习(Incremental Learning Through Deep Adaptation) 2018-05-25 18:56:00 木呆呆瓶子 阅读数 10564  收藏 更多 分 ...

  4. GOF 的23种JAVA常用设计模式总结 01 设计模式的概念分类和功能

    1.简介 软件设计模式(Software Design Pattern),又称设计模式,是一套被反复使用.多数人知晓的.经过分类编目的.代码设计经验的总结.它描述了在软件设计过程中的一些不断重复发生的 ...

  5. 一个 Vim 重度用户总结的 vim 超全指南

    我本人是 Vim 的重度使用者,就因为喜欢上这种双手不离键盘就可以操控一切的feel,Vim 可以让我对文本的操作更加精准.高效. 对于未使用过 Vim 的朋友来说,可能还无法体会到这种感觉.由于使用 ...

  6. 2019年北航OO第4单元(UML)总结

    1 架构设计 经过了接近一学期的程序设计训练,在这一单元的第一次作业中我就非常注重架构的设计,竭力避免像之前一样陷入"第一次作业凑合,第二次作业重构"的不健康的迭代模式.整体上来说 ...

  7. mongoose 警告信息 { useNewUrlParser: true } { useUnifiedTopology: true }

    问题: 解决:

  8. 反射,内置方法,__str__ __repr__

    反射 反射用到的mmp模块 def wahaha():print('wahaha') class QQxing: def __init__(self,name): self.name = name d ...

  9. Apache 安装后Error 403的故障排错方法(linux)

    Apache 安装后Error 403的故障排错方法 2018年01月07日 14:25:41 个人分类: Linux 一.问题描述 在apache2的httpd配置中,很多情况都会出现403. 刚安 ...

  10. linux 利用LDAP身份集中认证

    碰巧所在的公司用到了ldap 集中身份认证,所有打算研究下这套架构,但是看遍了网络上的很多教程,要么不完整,要么就是照着根本弄不出来,十月一研究了三天,结合八方资源终于弄出来了,真是不容易,哎,特此记 ...