LeetCode 380. Insert Delete GetRandom O(1)
380. Insert Delete GetRandom O(1)
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.
insert(val): Inserts an item val to the set if not already present.remove(val): Removes an item val from the set if present.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)的更多相关文章
- [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 ...
- 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). ...
- [LeetCode] 380. Insert Delete GetRandom O(1) 常数时间内插入删除和获得随机数
Design a data structure that supports all following operations in average O(1) time. insert(val): In ...
- LeetCode 380. Insert Delete GetRandom O(1) (插入删除和获得随机数 常数时间)
Design a data structure that supports all following operations in average O(1) time. insert(val): In ...
- [leetcode]380. Insert Delete GetRandom O(1)常数时间插入删除取随机值
Design a data structure that supports all following operations in average O(1) time. insert(val): In ...
- LeetCode 380. Insert Delete GetRandom O(1) 常数时间插入、删除和获取随机元素(C++/Java)
题目: Design a data structure that supports all following operations in averageO(1) time. insert(val): ...
- [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 ...
- [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 ...
- 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 ...
随机推荐
- Hadoop2.7.3 HA高可靠性集群搭建
1.背景介绍 Hadoop2.0.0之前,在一个HDFS集群中,NameNode存在单节点故障(SPOF):因为集群中只有一个NameNode,所以在使用过程中,如果该NameNode出现故障或数据丢 ...
- 这样才能使本地Mysql服务允许被外部主机连接(两步)
网上的N多方法都不全面,只有下面的第一步或第二步是不行的,必须同时执行下面两步操作: 修改mysql.user表 以root或debian-sys-maint身份登录mysql $ mysql -u ...
- iOS开发debug集锦
1.添加第三方库时,需要注意使用环境 duplicate symbol _llvm.embedded.module in: /Users/dengw/360Cloud/xcode_code/appli ...
- Windows下IIS+PHP 5.2的安装与配置
Windows下IIS+PHP 5.2的安装与配置 Windows下PHP的安装虽然简单,但如果不注意方法,仍然会让你头疼.此外,PHP 5.2版本与之前4.x版本也有一些不同,所以有必要记录一下 ...
- 转:WebClient类(温习一下)
WebClient类提供向 URI 标识的资源发送数据和从 URI 标识的资源接收数据的公共方法. 其实就相当于创建一个请求客户端.可以获取网页和各种各样的信息,包括交互. 通过MSDN来看看WebC ...
- ACM-ICPC 2018 沈阳赛区网络预赛 F. Fantastic Graph (上下界网络流)
正解: #include <bits/stdc++.h> using namespace std; const int INF = 0x3f3f3f3f; const int MAXN=1 ...
- 洛谷 P4211 [LNOI2014]LCA (树链剖分+离线)
题目:https://www.luogu.org/problemnew/solution/P4211 相当难的一道题,其思想难以用言语表达透彻. 对于每个查询,区间[L,R]中的每个点与z的lca肯定 ...
- 《UML和模式应用》读书笔记(一)面向对象分析和设计简单示例
在开始进行对象分析和设计之前,先通过“扔骰子”这个软件(游戏者扔两个骰子,如果总是是7,则赢,否则输),来简单分析下这个过程. 1:用例 需求分析,可能包括人们如何应用的场景或情节,这些都可以被编写成 ...
- 【转】使用DataConnectionDialog在运行时设置数据源连接字符串
介绍: DataConnectionDialog 类: 打开“数据连接”对话框,获取用户选择的数据连接信息. 命名空间为:Microsoft.Data.ConnectionUI 所在程序集:Micro ...
- iOS 大批量弹幕小论(粒子弹幕)
一.现状 如今直播类.视频播放器等基本都有弹幕模式. 为了保持性能和内存可控,基本是在初始化的时候生成一个Pool(Pool的容量是设定好的), 也就是利用重用机制(可以想象一下UITableView ...