原题链接在这里: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. unexpected end of file while looking for precompiled headerdirective Add directive to 'stdafx.h' or rebuild precompiled header错误

    解决方式: 项目工程右键->propertity(属性),选择不用于预编译头 原因: C++的编译过程如下: 当头文件很多时,预编译过程需要耗费大量时间,为了减少重复编译的次数,C和C++提供了 ...

  2. css3 网页图片轮播的实现

    .lunbo{ height: 640px; width: 100%; background-position: -280px; margin-top: 103px; -webkit-animatio ...

  3. Go语言( 函数)

    函数是组织好的.可重复使用的.用于执行指定任务的代码块.本文介绍了Go语言中函数的相关内容. 函数 Go语言中支持函数.匿名函数和闭包,并且函数在Go语言中属于“一等公民”. 函数定义 Go语言中定义 ...

  4. 【LEETCODE】40、1051. Height Checker

    package y2019.Algorithm.array; /** * @ProjectName: cutter-point * @Package: y2019.Algorithm.array * ...

  5. tkinter学习笔记_03

    6.单选框   Radiobutton import tkinter as tk root = tk.Tk() root.title("xxx") root.geometry('2 ...

  6. 爬虫 HttpHelper

    /// <summary> /// 类说明:HttpHelper类,用来实现Http访问,Post或者Get方式的,直接访问,带Cookie的,带证书的等方式,可以设置代理 /// 重要提 ...

  7. .net core使用ocelot---第五篇 服务质量

    简介 .net core使用ocelot---第一篇 简单使用  .net core使用ocelot---第二篇 身份验证使用 .net core使用ocelot---第三篇 日志记录  .net c ...

  8. 面试总结 转发(CSDN 博主)

    1 https://blog.csdn.net/jackfrued/article/details/44921941 2 https://blog.csdn.net/jackfrued/article ...

  9. LinuxKernel优秀博客

    1.vanbreaker的专栏 2.LinuxKernel Exploration 3.DroidPhone的专栏 4.Linux内核研究以及学习文档和ARM学习以及研究的开放文档   [力荐] 5. ...

  10. python 笔记二

    17.进程线程 进程间通信方式:管道Pipe:队列Queue:共享内存Value.Array.Manager: 多进程同步:锁Lock.递归锁RLock.Condition(条件变量):事件event ...