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

题目标签:Array, HashTable, Design
  题目让我们设计一个 数据结构, 能插入val, 删除val 和 获得 随机val ,并且是O(1) 时间。
  一开始想到的是HashSet,但是对于 取得随机val O(1) 肯定不行。
  所以,能在O(1) 时间内 获得随机项,肯定是array。那么这一题需要array 和 HashMap的配合使用。
  ArrayList nums 保存所有的val;HashMap 保存 所有的val 和 index(在nums)的映射。
 
  对于insert:nums 直接 add ,map 直接 put,都符合O(1);
  对于remove:map remove 符合O(1), 但是 nums remove的话,只有当remove 最后一项的时候,才符合O(1)。如果遇到的val 在nums 里不是最后一项的话,把最后一项的val 保存到 val 的位置,并且要更新最后一项在map中的index,然后nums remove 最后一项。
  对于getRandom:直接在nums 里随机返回就可以了。
 

Java Solution:

Runtime beats 86.91%

完成日期:09/16/2017

关键词:Array, Hash Table, Design

关键点:利用array 保存数值;利用map保存 - 数值 当作key,数值在array里的index 当作value。

 class RandomizedSet
{
private HashMap<Integer, Integer> map; // key is value, value is index
private ArrayList<Integer> nums; // store all vals
private java.util.Random rand = new java.util.Random(); /** Initialize your data structure here. */
public RandomizedSet()
{
map = new HashMap<>();
nums = new ArrayList<>();
} /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val)
{
boolean contain = map.containsKey(val); if(contain)
return false; map.put(val, nums.size());
nums.add(val); return true;
} /** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val)
{
boolean contain = map.containsKey(val);
if(!contain)
return false; int valIndex = map.get(val);
if(valIndex != nums.size() - 1) // if this val is not the last one
{
// copy the last one value into this val's position
int lastNum = nums.get(nums.size() - 1);
nums.set(valIndex, lastNum);
// update the lastNum index in map
map.put(lastNum, valIndex);
}
map.remove(val);
nums.remove(nums.size() - 1); // only remove last one is O(1) return true;
} /** Get a random element from the set. */
public int getRandom()
{
return nums.get(rand.nextInt(nums.size()));
}
} /**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet obj = new RandomizedSet();
* boolean param_1 = obj.insert(val);
* boolean param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/

参考资料:

https://discuss.leetcode.com/topic/53216/java-solution-using-a-hashmap-and-an-arraylist-along-with-a-follow-up-131-ms

LeetCode 题目列表 - LeetCode Questions List

 

LeetCode 380. Insert Delete GetRandom O(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. insert(val): In ...

  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) 、381. Insert Delete GetRandom O(1) - Duplicates allowed

    380. Insert Delete GetRandom O(1) 实现插入.删除.获得随机数功能,且时间复杂度都在O(1).实际上在插入.删除两个功能中都包含了查找功能,当然查找也必须是O(1). ...

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

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

  5. [leetcode]380. Insert Delete GetRandom 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) 常数时间插入、删除和获取随机元素(C++/Java)

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

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

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

随机推荐

  1. Linux入门_1

    Linux入门 目录  Root用户  终端  交互式接口(图形化界面和命令行)  什么是Shell(bash)  命令提示符  内部命令和外部命令 enable,hash  命令别名 ...

  2. Mysql的基本命令图

    如果看不清的,右键图片在新标签页打开! 这是经过我的整理出来的!如果有重要的再补充把-..

  3. Tiled Editor 图块的两种导入方式

    一.图块集图块的导入. 打开或者创建地图后,新建 新图块. 弹出新图块面板 图块类型选择 "基于图块集图块",一定要选择"嵌入地图",否则需要另存为其他类型的文 ...

  4. Java学习笔记二---设置环境变量JAVA_HOME,CLASSPATH,PATH

    1.环境变量包括: JAVA_HOME,CLASSPATH,PATH 2.设置环境变量的目的: 路径搜索,方便查找到jdk的安装路径.方便搜索用到的类文件.方便搜索用到的可执行文件如java,java ...

  5. 深入理解计算机系统chapter8

    进程轮流使用处理器 父进程调用fork来创建一个新的子进程 回收子进程 waitpid/wait 非本地跳转:

  6. javascript插入before(),after()新DOM方法

    随着web的技术突飞猛进的发展.HTML5 ES6等新技术的发展,与此同时DOM等标准也在悄悄的进步,各大浏览器也在悄悄的发展适配新的属性和方法,今天我们来看看Javascript新的DOM的方法 二 ...

  7. 进入css3动画世界(二)

    进入css3动画世界(二) 今天主要来讲transition和transform入门,以后会用这两种属性配合做一些动效. 注:本文面向前端css3动画入门人员,我对这个也了解不深,如本文写的有纰漏请指 ...

  8. android-蓝牙通信

    一:简介 由于项目曾经想用蓝牙通信,但由于蓝牙传输速度比较慢,最终还是没有使用蓝牙,不过还是在空闲之余研究了蓝牙通信,鉴于目前网上蓝牙这块教程并不多,尤其是从蓝牙扫描,蓝牙配对,蓝牙通信等完整的教程更 ...

  9. 基于maven创建和部署Webx项目

    1.准备工作 下载 Webx Maven 项目的目录结构Artifact插件. archetype-webx-quickstart-1.0.tar.gz插件:http://central.maven. ...

  10. 插入排序的性能测试对比(C与C++实现)

    一.概述: [标题]学生成绩管理的设计与实现 [开发语言]C.C++ [主要技术]结构体.STL [基本功能]实现对学生成绩类的基本操作:增加.删除.查询.排序 [测试数据]功能测试:按提示输入5组正 ...