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. 机器学习第7周-炼数成金-支持向量机SVM

    支持向量机SVM 原创性(非组合)的具有明显直观几何意义的分类算法,具有较高的准确率源于Vapnik和Chervonenkis关于统计学习的早期工作(1971年),第一篇有关论文由Boser.Guyo ...

  2. 关于websocket通讯

    var ws = { init:function(callback){ var _this = this; _this.callback = callback; }, websocket:functi ...

  3. 10、property

    成人的BMI数值:过轻:低于18.5正常:18.5-23.9过重:24-27肥胖:28-32非常肥胖, 高于32 体质指数(BMI)=体重(kg)÷身高^2(m) EX:70kg÷(1.75×1.75 ...

  4. Linux_Vi_命令

    Linux Vi 命令 ************************************************************************* 在vi中使用命令的方法是:冒 ...

  5. bash 获取时间段内的日志内容

    需求,获取时段内的/var/log/messages文件内出现错误的消息,支持多行的消息,支持天,小时分钟,秒级的区间,可以修改监控的日志对象 #!/bin/bash if [ $# != 1 ] ; ...

  6. Java线程的几个概念

    线程的生命周期: 新建状态:用new语句创建的线程对象处于新建状态,此时它和其它的java对象一样,仅仅在堆中被分配了内存 就绪状态:当一个线程创建了以后,其他的线程调用了它的start()方法,该线 ...

  7. ABP官方文档翻译 1.2 N层架构

    N层架构 介绍 ABP架构 其他(通用) 领域层 应用层 基础设施层 网络和展现层 其他 总结 介绍 应用程序代码库的分层架构是被广泛认可的可以减少程序复杂度.提高代码复用率的技术.为了实现分层架构, ...

  8. 第三方CSS安全吗?

    原文:https://jakearchibald.com/201...翻译:疯狂的技术宅 本文首发微信公众号:jingchengyideng欢迎关注,每天都给你推送新鲜的前端技术文章 前一段时间,有很 ...

  9. 20145322 《Java程序设计》第6周学习总结

    20145322 <Java程序设计>第6周学习总结 教材学习内容总结 第十章 10.1.1 串流设计的概念 Java将输入/输出抽象化为串流,数据有来源及目的地,衔接两者的是串流对象. ...

  10. java 普通内部类和静态内部类

    区别1: 普通内部类实例化后的对象持有外部类的引用,在非静态类内部可以访问外部类的成员:静态内部类实例化不持有外部对象引用,不能访问外面的方法和成员: 从耦合度上来讲,普通内部类跟外部类耦合程度很高, ...