[抄题]:

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

[暴力解法]:

时间分析:

空间分析:

[优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

如果hashmap的value为空,则必须把key也删掉

[思维问题]:

[一句话思路]:

用set存location, 然后还是先移动 后删除

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. 提前判断存在性还是需要的,因为如果不存在时,需要初始化一个hashset
  2. map中存的是nums数组的大小,表示目前元素插入成为了新数组最后一位:nums.size()
  3. nums.remove(index,不是内容)

[二刷]:

[三刷]:

[四刷]:

[五刷]:

[五分钟肉眼debug的结果]:

[总结]:

hashset可以分区

[复杂度]:Time complexity: O() Space complexity: O()

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[算法思想:递归/分治/贪心]:

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

[代码风格] :

class RandomizedCollection {

    /** Initialize your data structure here. */
HashMap<Integer, Set<Integer>> map;
ArrayList<Integer> nums;
java.util.Random rand = new java.util.Random(); public RandomizedCollection() {
map = new HashMap<Integer, Set<Integer>>();
nums = new ArrayList<>();
} /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
public boolean insert(int val) {
boolean contain = map.containsKey(val);
if (!contain) map.put(val, new HashSet<Integer>()); map.get(val).add(nums.size());
nums.add(val); return !contain;
} /** Removes a value from the collection. Returns true if the collection contained the specified element. */
public boolean remove(int val) {
boolean contain = map.containsKey(val);
if (!contain) return false; int loc = map.get(val).iterator().next();
//renew location
if (loc < nums.size() - 1) {
int lastone = nums.get(nums.size() - 1);
nums.set(loc, lastone);
map.get(lastone).add(loc);
map.get(lastone).remove(nums.size() - 1);
} //remove, if key is empty
nums.remove(nums.size() - 1);
map.get(val).remove(loc);
if (map.get(val).isEmpty()) map.remove(val); //return
return true;
} /** Get a random element from the collection. */
public int getRandom() {
return nums.get(rand.nextInt(nums.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();
*/

381. Insert Delete GetRandom O(1) - Duplicates allowed允许重复的设计1数据结构的更多相关文章

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

  2. 381. 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 常数时间内插入删除和获得随机数 - 允许重复

    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)时间 - 允许重复

    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

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

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

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

  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. 381 Insert Delete GetRandom O(1) - Duplicates allowed O(1) 时间插入、删除和获取随机元素 - 允许重复

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

随机推荐

  1. QT creator 调试问题

    问题:debug出现“ptrace:不允许的操作.” 解决办法: # may not be appropriate for developers or servers with only admin ...

  2. 561. 数组拆分 I

    题目 python class Solution: def arrayPairSum(self, nums): """ :type nums: List[int] :rt ...

  3. json工具性能比较:json-lib和jackson进行Java对象到json字符串序列化[转]

    网上查找“java json”,发现大家使用最多的还是json-lib来进行java对象的序列化成json对象和反序列化成java对象的操作.但是之前在网上也看到过一往篇关于json序列化性能比较的文 ...

  4. Windows Server 2012十大实用快捷键组合

    在本文中,我们将一起体验快捷键如何在微软最新服务器操作系统中帮助用户提升工作效率. 微软推出的最新服务器操作系统比我印象中任何一款前代Windows Server产品都依赖于键盘操作——当然,这些产品 ...

  5. 记录关于ubuntu无线上网只能ping通5~7个数据包的问题

    问题是这样的,我的笔记本(ubuntu desktop)连接上wifi后,信号很好,但是上网上不了,ping网关也不通,ping外网仅仅只有当笔记本刚刚连接上wifi的时候能ping通5至6个包,然后 ...

  6. java之IO整理(中)

    一:打印流/*System.out.println()重定向输出*/ /*public static void main(String[] args) { System.out.println(&qu ...

  7. Python web框架 Tornado(三)自定义session组件

    我们在学习Django框架的过程中,内部封装了session组件,以方便于我们使用进行验证.但是Tornado框架是没有session的,所以如果想使用session的话,就需要我们自己定制相对应的组 ...

  8. cobalt strike 第一节连接到团队的服务器

    介绍:Cobalt Strike 一款以metasploit为基础的GUI的框架式渗透工具,集成了端口转发.服务扫描,自动化溢出,多模式端口监听,win exe木马生成,win dll木马生成,jav ...

  9. pvalue for go kegg enrichment

      Simple, fast implementation of Fisher’s exact test. . For example, for the following table: o Havi ...

  10. RPC框架的服务注册和发现

    https://www.cnblogs.com/valor-xh/p/6281502.html https://blog.csdn.net/listslim1/article/details/5157 ...