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 1 is the only number in the set, getRandom always return 1.
randomSet.getRandom();

设计一个数据结构在O(1)时间内完成:insert(val),remove(val),getRandom()

由于是O(1)时间,要用哈希表 + 数组(HashMap + Array),数组用来保存数字,哈希表用来建立每个数字和其在数组中的位置之间的映射。

插入操作:先判断是否在HashMap里,如果存在则不需要插入,直接返回false。不存在的话,把此数插入到数组的末尾,然后在HashMap中建立数字和其位置的映射。

删除操作:先判断是否在HashMap里,如果没有,直接返回false。由于HashMap的删除是O(1)时间,而数组并不是。为了保证了O(1)时间内的删除,把要删除的数字和数组的最后一个数调换个位置,然后修改对应的HashMap中的值,删除数组的最后一个元素即可。

返回随机数:随机生成一个数组位置,返回该位置上的数字。

Java:

public class RandomizedSet {
Map<Integer, Integer> map;//<val, index in arrlist>
List<Integer> list;//keep a record of value for get random
int size;//map and list are the same size
Random rand;
/** Initialize your data structure here. */
public RandomizedSet() {
this.map = new HashMap<>();
this.list = new ArrayList<>();
this.size = 0;
this.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, size);
list.add(val);
size++;
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)){
int last = list.get(size - 1);
list.set(map.get(val), last);//use last added ele to fill the element to be removed
map.put(last, map.get(val));//update last added ele's index in list
map.remove(val);
list.remove(size - 1);//remove at end is constant
size--;
return true;
}
return false;
} /** Get a random element from the set. */
public int getRandom() {
return list.get(rand.nextInt(size));
}
}

Python:

import random
class RandomizedSet(object): def __init__(self):
"""
Initialize your data structure here.
"""
self.dataMap = {}
self.dataList = [] def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
:type val: int
:rtype: bool
"""
if val in self.dataMap:
return False
self.dataMap[val] = len(self.dataList)
self.dataList.append(val)
return True def remove(self, val):
"""
Removes a value from the set. Returns true if the set contained the specified element.
:type val: int
:rtype: bool
"""
if val not in self.dataMap:
return False
idx = self.dataMap[val]
tail = self.dataList.pop()
if idx < len(self.dataList):
self.dataList[idx] = tail
self.dataMap[tail] = idx
del self.dataMap[val]
return True def getRandom(self):
"""
Get a random element from the set.
:rtype: int
"""
return random.choice(self.dataList)  

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;
nums.push_back(val);
m[val] = nums.size() - 1;
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 last = nums.back();
m[last] = m[val];
nums[m[val]] = last;
nums.pop_back();
m.erase(val);
return true;
} /** Get a random element from the set. */
int getRandom() {
return nums[rand() % nums.size()];
}
private:
vector<int> nums;
unordered_map<int, int> m;
};

类似题目:

[LeetCode] 381. Insert Delete GetRandom O(1) - Duplicates allowed 插入删除和获得随机数O(1)时间 - 允许重复  

All LeetCode Questions List 题目汇总

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

    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. 性能测试基础---URL和HTTP协议

    ·URL和HTTP协议: ·URL构成: URL是web应用进行资源访问的主要方式.一般来说,由五个部分构成: 示例:http://192.168.2.212/phpwind1/searcher.ph ...

  2. python代码规范 自动优化工具Black

    自动优化工具Black 在众多代码格式化工具中,Black算是比较新的一个,它***的特点是可配置项比较少,个人认为这对于新手来说是件好事,因为我们不必过多考虑如何设置Black,让 Black 自己 ...

  3. python笔记35-装饰器

    前言 python装饰器本质上就是一个函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外的功能,装饰器的返回值也是一个函数对象. 很多python初学者学到面向对象类和方法是一道大坎,那么p ...

  4. springboot在idea的RunDashboard如何显示出来

    找到.idea文件下的workspace.xml,并找到RunDashboard 加入如下配置 <option name="configurationTypes"> & ...

  5. 使用mybatis框架实现带条件查询-多条件(传入Map集合)

    我们发现我们可以通过传入javaBean的方式实现我们的需求,但是就两个条件,思考:现在就给他传入一个实体类,对系统性能的开销是不是有点大了. 现在改用传入Map集合的方式: 奥!对了,在创建map集 ...

  6. VSFTPD匿名用户上传文件

    1.安装vsftpd yum -y install vsftpd yum -y install ftp 客户端 2.编写配置文件 vim /etc/vsftpd/vsftpd.conf anonymo ...

  7. maven install

    1. install maven under ubuntu apt install maven 2 speed up package download vim ~/.m2/settings.xml & ...

  8. 2-STM32+W5500+GPRS(2G)基础篇-(W5500-学习说明)

    https://www.cnblogs.com/yangfengwu/p/11220042.html 定版: 这一节先直接说明怎么把官方的源码应用在我做的这块开发板上 https://www.w550 ...

  9. lettcode 上的几道哈希表与链表组合的数据结构题

    目录 LRU缓存 LFU缓存 全O(1)的数据结构 lettcode 上的几道哈希表与链表组合的数据结构题 下面这几道题都要求在O(1)时间内完成每种操作. LRU缓存 LRU是Least Recen ...

  10. [RN] React Native 下实现底部标签(支持滑动切换)

    上一篇文章 [RN] React Native 下实现底部标签(不支持滑动切换) 总结了不支持滑动切换的方法,此篇文章总结出 支持滑动 的方法 准备工作之类的,跟上文类似,大家可点击上文查看相关内容. ...