380. Insert Delete GetRandom O(1)

Add to List

Description Submission Solutions

  • Total Accepted: 21771
  • Total Submissions: 56175
  • Difficulty: Medium
  • Contributors: Admin

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

Subscribe to see which companies asked this question.

【题目分析】

设计一种数据结构,使得插入,删除和随机获取一个值的时间复杂度为O(1).

【思路】

1. 随机读取一个数的话,使用数组的时间复杂度是最小的,因为通过下标可以直接定位。考虑到元素会不断插入,我们可以选择ArrayList来存储我们的元素。

2. 要删除一个元素,在数组中需要遍历才能找到这个元素。而在HashMap中,可以快速定位一个元素。因此我们可以用HashMap来存储元素和它在ArrayList中对应的下标。

通过以上的分析,我们知道了数据结构该如何设计。

【java代码】

 public class RandomizedSet {
Map<Integer, Integer> map;
List<Integer> list;
Random random; /** Initialize your data structure here. */
public RandomizedSet() {
map = new HashMap<>();
list = new ArrayList<>();
random = new Random();
} /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
if(map.containsKey(val)) return false;
map.put(val, list.size());
list.add(val);
return true;
} /** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
if(!map.containsKey(val)) return false;
int loc = map.get(val);
if(loc < list.size()-1) {
int last = list.get(list.size()-1);
list.set(loc, last);
map.put(last, loc);
}
map.remove(val);
list.remove(list.size()-1);
return true;
} /** Get a random element from the set. */
public int getRandom() {
return list.get(random.nextInt(list.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();
*/

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

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

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

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

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

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

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

随机推荐

  1. Delphi APP 開發入門(八)SQLite資料庫

    Delphi APP 開發入門(八)SQLite資料庫 分享: Share on facebookShare on twitterShare on google_plusone_share   閲讀次 ...

  2. centos7命令3

    查看监听的端口 netstat -lntp 检查端口被哪个进程占用 netstat -lnp|grep 8080 查看当前文件夹大小 du -sh 查看当前文件夹各目录大小 du -sh ./* 查看 ...

  3. 利用page_source抓取网页中的URL,进行链接测试

    selenium的page_source方法可以获取到页面源码,下面就把它应用到链接测试中. # coding:utf-8 __author__ = 'helen' import re,request ...

  4. sgu 103 Traffic Lights 解题报告及测试数据

    103. Traffic Lights Time limit per test: 0.25 second(s) Memory limit: 4096 kilobytes 题解: 1.其实就是求两点间的 ...

  5. Lua 基础总结

    lua 数组下标从 1 开始, 不是 0 lua 逻辑运算符  与 或 非  就是英文  and  or  not local  局部变量 数据类型:lua是一门动态类型语言,变量没有类型,只有值才有 ...

  6. TOSCA自动化测试工具--openURL

    在folder下面create test case 输入自己的url,actionMode 是input, String类型

  7. [入坑系列] Mybatis 中$与#的区别

    1.理解 1 #是将传入的值当做字符串的形式,eg:select id,name,age from student where id =#{id},当前端把id值1,传入到后台的时候,就相当于 sel ...

  8. 【Error】安装程序无法打开注册表项 UNKNOWN\Components\...

    在安装程序的时候出现错误信息: 解决方法: 依次点击开始,所有程序,附件,右键单击命令提示符,选择以管理员身份运行.运行secedit /configure /cfg %windir%\inf\def ...

  9. java压缩多个文件

    首先创建一个工具类,定义好接口,这里的参数1:fileList:多个文件的path+name2: zipFileName:压缩后的文件名 下面是代码,注释已经很详细了 public class ZIP ...

  10. @Override笔记

    作用:用来保证正确重写方法,当你重写方法出错时,比如方法名误写,或者漏掉参数,编译器会提示编译错误. 使用场景:继承父类,重写父类方法:实现接口,实现接口方法. 备注:jdk1.5之允许在继承时使用, ...