[抄题]:

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. [LeetCode系列]最大连续子列递归求解分析

    本文部分参考Discuss: LeetCode. 步骤1. 选择数组的中间元素. 最大子序列有两种可能: 包含此元素/不包含. 步骤2. 步骤2.1 如果最大子序列不包含中间元素, 就对左右子序列进行 ...

  2. 【转】简述configure、pkg-config、pkg_config_path三者的关系

    原文网址:http://www.mike.org.cn/articles/description-configure-pkg-config-pkg_config_path-of-the-relatio ...

  3. Avro和Thrift区别(未完待续)

    两者都是优秀的序列化框架: Avro创造之初是Hadoop之父Doug为了创造一种更加快捷的序列化方案(此时已经有了thrift),用于Hadoop的HDFS的文件序列化问题. Thrift一个成熟的 ...

  4. OpenCL入门

    初入OpenCL,做个记录. 在Windows下开发OpenCL程序,必须先下载OpenCL的SDK,现在AMD,NVIDIA,Intel均提供各自的OpenCL库,基本是大同小异.安装好SDK后新建 ...

  5. yii2自定义500错误

    由于项目想加预警监控,有一块儿是涉及到程序内部错误的500,这样的错误级别比较高,所以就需要捕获这样的错误,顺便自定义了一把视图样式 看了这篇博客,知道了如何去自定义自己错误页面 : http://t ...

  6. PyQt 5控件

    PyQt 5控件包括:按钮.复选框.滑动条.列表框等 复选框QCheckBox QCheckBox复选框控件,它有两个状态:打开和关闭,他是一个带有文本标签(Label)的控件.复选框常用于表示程序中 ...

  7. ubuntu16.04编译QT5.6所依赖的库

    首先在QT的根目录下,阅读README文件! 里面介绍了ubuntu环境下,编译该版本的QT需要安装的包 New dependencies in Qt 5    ------------------- ...

  8. nginx与tomcat整合

    nginx与tomcat整合   1. 在/usr/local/nginx/conf下面添加文件proxy.conf # cat /usr/local/nginx/confg/proxy.conf p ...

  9. python变量、引用、拷贝之间的关系

    Python中一切皆为对象,不管是集合变量还是数值型or字符串型的变量都是一个引用,都指向对应内存空间中的对象. 简而言之: 变量直接赋值:新变量本身及其内部的元素都与原变量指向相同的内存空间,并且值 ...

  10. 详解Vue2.0生命周期

    网上已经有很多关于vue生命周期的文章,我的这篇文章的由来,其实是我对官网上描述的一句话的思考与理解:“el被新创建的vm.$el替换”,所以文章更多的内容可能是在对vue生命周期中“created ...