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

class RandomizedSet {

    private Map<Integer, Integer> map;
private List<Integer> list;
private Random rand;
/** Initialize your data structure here. */
public RandomizedSet() {
map = new HashMap<>();
list = new ArrayList<>();
rand = 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 index = map.remove(val);
int lastValue = list.remove(list.size() - 1);
if (val != lastValue) {
// need to fill back the removal list index
list.set(index, lastValue);
map.put(lastValue, index);
}
return true;
} /** Get a random element from the set. */
public int getRandom() {
return list.get(rand.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();
*/

[LC] 380. Insert Delete GetRandom O(1)的更多相关文章

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

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

  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) 解题报告(Python)

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

  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) 插入删除获得随机数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. 380. Insert Delete GetRandom O(1) 设计数据结构:在1的时间内插入、删除、产生随机数

    [抄题]: Design a data structure that supports all following operations in average O(1) time. insert(va ...

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

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

  9. LeetCode 380. Insert Delete GetRandom O(1) 常数时间插入、删除和获取随机元素(C++/Java)

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

随机推荐

  1. js判断苹果和安卓端或者wp端

    最近做了一个H5,说要提供一个底部,可以区分安卓或者ios,到相应的网址进行下载APP,如图: 代码如下:  window.onload = function () { var u = navigat ...

  2. linux下ffmpeg环境搭建记录

    1.Linux下安装yasm 官网下载:http://yasm.tortall.net/Download.html tar -zvxf yasm-1.3.0.tar.gz cd yasm-1.3.0/ ...

  3. 36. docker swarm docker secret 的使用和管理

    1.secret management 的作用 用来存储 其他人不想看到 的数据 2.secret management 存在 swarm manager 节点 raft database 里. se ...

  4. Log4Net 使用及组合公共类

    好记性不如烂笔头,这次是由衷的感受到了! log4net 是一个很好用的日志记录工具,引用入项目中,如何查看项目内部运行情况,如何快速定位异常信息,好的日志记录能帮很大的忙: log4net 很好用, ...

  5. 项目常用JS方法封装--奋斗的IT青年(微信公众号)

                                                                                                        ...

  6. 201509-1 数列分段 Java

    思路: 后一个和前一个不相等就算一段 import java.util.Scanner; public class Main { public static void main(String[] ar ...

  7. 68)deque数组

    基本要求: 1)和vecctor基本区别   示意图 vector在尾部添加和删除, deque在尾部添加和删除,在头部添加和删除. 2)基本知识: 3)deque的构造形式:   4)基本操作和遍历 ...

  8. 吴裕雄--天生自然TensorFlow高层封装:Estimator-自定义模型

    # 1. 自定义模型并训练. import numpy as np import tensorflow as tf from tensorflow.examples.tutorials.mnist i ...

  9. 【网易官方】极客战记(codecombat)攻略-森林-流星雨star-shower

    流星雨不仅是一个了不起的现象,而且是获得一些钱的好机会. 简介 流星雨正在下着你的宝石和硬币! 但星形金属不是很长寿,硬币很快就消失了. 宝石不会消失. 使用或语句提取密切的金币或宝石: if ite ...

  10. java通过HSSFWorkbook导出xls文件

    使用swgger2.Restlet等接口工具有bug导致导出失败,测试直接使用浏览器 //导出列表-新 @UserRoleJudgment(authpos = SystemControllerLog. ...