题目:

Design a data structure that supports all following operations in averageO(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();

分析:

设计一个数据结构支持以下几个操作。

insert(val): 当元素 val 不存在时,向集合中插入该项。
remove(val): 元素 val 存在时,从集合中移除该项。
getRandom: 随机返回现有集合中的一项。每个元素应该有相同的概率被返回。

我们使用HashMap来支持插入和移除操作,利用数组来支持对数据的随机访问。插入元素时,将val和该val在数组中索引值存入map中,新插入的元素实际上在数组中的索引就是数组还有元素的个数,将元素加到动态数组的尾端。

移除元素时,为了能够达到O(1),除了将val在map中移除,还要对数组进行操作,如果单纯的将val所对应的索引处的元素删除,由于后续的所有元素都要向前移动,这样会浪费大量的时间。我们知道数组移除最后一个元素的时间复杂度时O(1),我们将要移除的元素和数组的最后一个元素交换,也可以将最后一个元素覆盖到要移除元素的位置,同时修改最后一个元素在map中对应的索引,最后删除掉数组最后一个元素,就可以保证常数时间的移除操作。最后在数组大小的范围内产生随机数,返回对应的元素,即可实现随机访问。

程序:

C++

class RandomizedSet {
public:
/** Initialize your data structure here. */
RandomizedSet() { } /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
bool insert(int val) {
if(m.count(val))
return false;
m[val] = v.size();
v.push_back(val);
return true;
} /** Removes a value from the set. Returns true if the set contained the specified element. */
bool remove(int val) {
if(!m.count(val))
return false;
int index = m[val];
m[v.back()] = index;
v[index] = v.back();
m.erase(val);
v.pop_back();
return true;
} /** Get a random element from the set. */
int getRandom() {
int index = rand() % v.size();
return v[index];
}
private:
unordered_map<int, int> m;
vector<int> v;
};

Java

class RandomizedSet {

    /** Initialize your data structure here. */
public RandomizedSet() { } /** 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.get(val);
map.put(list.get(list.size()-1), index);
list.set(index, list.get(list.size()-1));
list.remove(list.size()-1);
map.remove(val);
return true;
} /** Get a random element from the set. */
public int getRandom() {
Random r = new Random();
return list.get(r.nextInt(list.size()));
}
private HashMap<Integer, Integer> map = new HashMap<>();
private ArrayList<Integer> list = new ArrayList<>();
}

LeetCode 380. Insert Delete GetRandom O(1) 常数时间插入、删除和获取随机元素(C++/Java)的更多相关文章

  1. [leetcode]380. Insert Delete GetRandom 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) 常数时间内插入删除和获得随机数

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

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

  4. [LeetCode] 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)

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

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

  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)设计数据结构,实现存,删,随机取的时间复杂度为O(1)

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

随机推荐

  1. Java并发编程系列-(9) JDK 8/9/10中的并发

    9.1 CompletableFuture CompletableFuture是JDK 8中引入的工具类,实现了Future接口,对以往的FutureTask的功能进行了增强. 手动设置完成状态 Co ...

  2. 001JZ2440开发板熟悉与使用

  3. $BZOJ1799\ Luogu4127$ 月之谜 数位统计$DP$

    AcWing Description Sol 看了很久也没有完全理解直接$DP$的做法,然后发现了记搜的做法,觉得好棒! 这里是超棒的数位$DP$的记搜做法总结   看完仿佛就觉得自己入门了,但是就像 ...

  4. Linux Centos7 环境搭建Docker部署Zookeeper分布式集群服务实战

    Zookeeper完全分布式集群服务 准备好3台服务器: [x]A-> centos-helios:192.168.19.1 [x]B-> centos-hestia:192.168.19 ...

  5. ruby 输出彩色内容到控制台

    程序输出控制台时,为了区分输出信息的严重程度,可以使用颜色.符号等来做标识. ruby 也支持设置输出内容的颜色,比如运行以下代码: 以下内容是百度到的,因发现很多博客都是同样的写法,所以出处反而没法 ...

  6. jenkins介绍和安装

    1.jenkins介绍 1.1 Jenkins概念: • Jenkins是一个功能强大的应用程序,允许持续集成和持续交付项目,无论用的是什么平台. • 这是一个免费的源代码,可以处理任何类型的构建或持 ...

  7. Lincode刷题No.8

    8.Rotate String lintcode 题解1: class Solution { public: /** * @param str: An array of char * @param o ...

  8. iOS滤镜系列-滤镜开发概览

    概述 滤镜最早的出现应该是应用在相机镜头前实现自然光过滤和调色的镜片,然而在软件开发中更多的指的是软件滤镜,是对镜头滤镜的模拟实现.当然这种方式更加方便快捷,缺点自然就是无法还原拍摄时的真实场景,例如 ...

  9. 【Java基础总结】数据库编程

    MySQL数据库查询 import java.sql.*; public class JdbcDemo1{ public static void main(String[] args){ try{ / ...

  10. ArcEngine语法笔记(VB)

    1.获取图层字段 Dim pTable As ITable = pLayer Dim pField As IField pField = pTable.Fields.Field(i) Next  2. ...