[抄题]:

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

  1. insert(val): Inserts an item val to the set if not already present.
  2. remove(val): Removes an item val from the set if present.
  3. getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.

Example:

// Init an empty set.
RandomizedSet randomSet = new RandomizedSet(); // Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomSet.insert(1); // Returns false as 2 does not exist in the set.
randomSet.remove(2); // Inserts 2 to the set, returns true. Set now contains [1,2].
randomSet.insert(2); // getRandom should return either 1 or 2 randomly.
randomSet.getRandom(); // Removes 1 from the set, returns true. Set now contains [2].
randomSet.remove(1); // 2 was already in the set, so return false.
randomSet.insert(2); // Since 2 is the only number in the set, getRandom always return 2.
randomSet.getRandom();

[暴力解法]:

时间分析:

空间分析:

[优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

以前不知道这类题在干嘛:其实就是自己用一种数据结构,实现另一种数据结构

[一句话思路]:

为了保证随机生成的概率均衡,数组必须保持满格,只能从最后一位删除

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

[画图]:

[一刷]:

  1. 提前备注,别忘了加return

[二刷]:

[三刷]:

[四刷]:

[五刷]:

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

[总结]:

其实就是自己用一种数据结构,实现另一种数据结构

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

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

新建随机对象、利用随机数方法:

 java.util.Random rand = new java.util.Random(); 类名首字母大写
nums.get( rand.nextInt(nums.size()) );

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

[关键模板化代码]:

[其他解法]:

[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();
*/

380. Insert Delete GetRandom O(1) 设计数据结构:在1的时间内插入、删除、产生随机数的更多相关文章

  1. [leetcode]380. Insert Delete GetRandom O(1)设计数据结构,实现存,删,随机取的时间复杂度为O(1)

    题目: Design a data structure that supports all following operations in average O(1) time.1.insert(val ...

  2. LeetCode 380. Insert Delete GetRandom O(1)

    380. Insert Delete GetRandom O(1) Add to List Description Submission Solutions Total Accepted: 21771 ...

  3. 【LeetCode】380. Insert Delete GetRandom O(1) 解题报告(Python)

    [LeetCode]380. Insert Delete GetRandom O(1) 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxu ...

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

  5. [LeetCode] 380. Insert Delete GetRandom O(1) 插入删除获得随机数O(1)时间

    Design a data structure that supports all following operations in average O(1) time. insert(val): In ...

  6. [LeetCode] 380. Insert Delete GetRandom O(1) 常数时间内插入删除和获得随机数

    Design a data structure that supports all following operations in average O(1) time. insert(val): In ...

  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) 常数时间插入、删除和获取随机元素(C++/Java)

    题目: Design a data structure that supports all following operations in averageO(1) time. insert(val): ...

  9. [leetcode]380. Insert Delete GetRandom O(1)常数时间插入删除取随机值

    Design a data structure that supports all following operations in average O(1) time. insert(val): In ...

随机推荐

  1. [LeetCode系列]有序链表转换为平衡BST的递归解法

    给定有序链表(元素由小到大), 试问如何将其转换为一个平衡BST? 平衡BST: 任意节点的左右子树的深度差值不大于1. 主要思想是用递归. Trick是使用快慢指针来获取中间节点. 获得中间节点后, ...

  2. IIS6自带FTP安装及配置方法

    参考:http://v.huweishen.com/video/9.html ·IIS自带的FTP服务是最安全的,不会像Serv-U那样存在各种漏洞:但其配置过程也比较复杂. ·本节将以虚拟目录方式, ...

  3. NumPy-快速处理数据--ndarray对象--多维数组的存取、结构体数组存取、内存对齐、Numpy内存结构

    本文摘自<用Python做科学计算>,版权归原作者所有. 上一篇讲到:NumPy-快速处理数据--ndarray对象--数组的创建和存取 接下来接着介绍多维数组的存取.结构体数组存取.内存 ...

  4. 在 myeclipse中进行连接sql server的测试

    在 myeclipse中,连接 sql server 用的 url connection 与 java 代码 连接的 url值完全相同. (一下为 java的jdbc连接 sql server 成功的 ...

  5. sprinboot+redis

    (1)pom.xml引入jar包,如下: <dependency> <groupId>org.springframework.boot</groupId> < ...

  6. cordova 安装使用

    前人总结: Cordova是Apache软件基金会的一个产品.其前身是PhoneGap,由Nitobi开发,2011年10月,Adobe收够了Nitobi,并且PhoneGap项目也被贡献给Apach ...

  7. linux下进程cpu占用过高问题定位方法

    背景 记得前段时间,同事说他们测试环境的服务器cpu使用率一直处于100%,本地又没有什么接口调用,为什么会这样?cpu使用率居高不下,自然是有某些线程一直占用着cpu资源,那又如何查看占用cpu较高 ...

  8. 反向生成hibernate实体类和映射文件

    工欲善其事,必先利其器.我们可以使用IDE来根据数据库中的表反向生成实体类和映射文件,虽然这些东西手写也并不是难度很大,但是如果存在大量的简单工作需要我们做,也会显得很麻烦. 写在前面 我们反向生成的 ...

  9. 升级phpcms的ckeditor编辑器

    首先说明一下为什么升级?网上很多人升级成了ueditor,可从fckedotror 到 ckeditor,我个人都是比较喜欢的,特别是开放式的插件方式.另外一个就是至少要懂得升级和插件的开发,这样也能 ...

  10. SQL Server 全文索引的硬伤

    本文关键字:SQL Server全文索引.CONTAINS.FREETEXT.CONTAINSTABLE.FREETEXTTABLE等谓词. 想象这样一个场景:在DataBase_name.dbo.T ...