LeetCode 380. Insert Delete GetRandom O(1) (插入删除和获得随机数 常数时间)
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();
Java Solution:
Runtime beats 86.91%
完成日期:09/16/2017
关键词:Array, Hash Table, Design
关键点:利用array 保存数值;利用map保存 - 数值 当作key,数值在array里的index 当作value。
class RandomizedSet
{
private HashMap<Integer, Integer> map; // key is value, value is index
private ArrayList<Integer> nums; // store all vals
private java.util.Random rand = new java.util.Random(); /** Initialize your data structure here. */
public RandomizedSet()
{
map = new HashMap<>();
nums = new ArrayList<>();
} /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val)
{
boolean contain = map.containsKey(val); if(contain)
return false; map.put(val, nums.size());
nums.add(val); return true;
} /** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val)
{
boolean contain = map.containsKey(val);
if(!contain)
return false; int valIndex = map.get(val);
if(valIndex != nums.size() - 1) // if this val is not the last one
{
// copy the last one value into this val's position
int lastNum = nums.get(nums.size() - 1);
nums.set(valIndex, lastNum);
// update the lastNum index in map
map.put(lastNum, valIndex);
}
map.remove(val);
nums.remove(nums.size() - 1); // only remove last one is O(1) return true;
} /** Get a random element from the set. */
public int getRandom()
{
return nums.get(rand.nextInt(nums.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();
*/
参考资料:
https://discuss.leetcode.com/topic/53216/java-solution-using-a-hashmap-and-an-arraylist-along-with-a-follow-up-131-ms
LeetCode 题目列表 - LeetCode Questions List
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)
380. Insert Delete GetRandom O(1) Add to List Description Submission Solutions Total Accepted: 21771 ...
- 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) 常数时间插入、删除和获取随机元素(C++/Java)
题目: Design a data structure that supports all following operations in averageO(1) time. insert(val): ...
- LeetCode 381. Insert Delete GetRandom O(1) - Duplicates allowed (插入删除和获得随机数 常数时间 允许重复项)
Design a data structure that supports all following operations in average O(1) time. Note: Duplicate ...
- [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 ...
随机推荐
- JAVA多线程高并发学习笔记(三)——Callable、Future和FutureTask
为什么要是用Callable和Future Runnable的局限性 Executor采用Runnable作为基本的表达形式,虽然Runnable的run方法能够写入日志,写入文件,写入数据库等操作, ...
- MySql导入导出数据方法
导出全库备份到本地的目录 mysqldump -u$USER -p$PASSWD -h127.0.0.1 -P3306 --routines --default-character-set=utf8 ...
- [09] 监听器 Listener
1.事件 1.1 事件的概念 在Servlet中有一个概念叫做监听,顾名思义,就是监听某种事件是否发生.就如你是一家娱乐媒体公司的老板,你派出狗仔队去跟着某些明星,比如你想了解他们的绯闻,或者活动进展 ...
- Spring配置属性文件
在项目开发阶段和交付阶段数据库的连接信息往往是不同的,可以把这些信息写成属性文件,再在Spring中导入即可引用 jdbc.properties属性文件如下: jdbc.driverClassName ...
- 使用Spring的JavaConfig 和 @Autowired注解与自动装配
1 JavaConfig 配置方法 之前我们都是在xml文件中定义bean的,比如: 1 2 3 4 5 6 7 8 <beans xmlns="http://www.springf ...
- 常见注入手法第二讲,APC注入
常见注入手法第二讲,APC注入 转载注明出处 首先,我们要了解下什么是APC APC 是一个简称,具体名字叫做异步过程调用,我们看下MSDN中的解释,异步过程调用,属于是同步对象中的函数,所以去同步对 ...
- [python学习笔记] 运算符
数学运算符 与大多语言相同的运算符就不介绍了.不同的地方会用 (!不同)标出 与java相同的运算符 , - , * , % , / 不同之处 除法 (!不同) / 与java不同,整数相除,结果为 ...
- JavaScript 框架------------AngularJS(上)
一.简单了解一下AngularJS AngularJS 是一个 JavaScript 框架.它可通过 <script> 标签添加到 HTML 页面. AngularJS 通过 指令 扩展了 ...
- 在Storyboard中为UITableView添加Header和Footer
我在这里所说的Header和Footer并不是sectionHeader和sectionFooter,而是指UITableView的tableHeaderView和tableFooterView,这两 ...
- oss滤网图片音视频过滤(1)内容检测
图片音视频过滤有好多方法,我这里就不一一介绍了,这篇文章只是简单介绍一下我在项目中使用阿里云oss滤网过滤的步骤 1.所遇问题: 1.图片视频鉴别时要设置textScanRequest.setUriP ...