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 ...
随机推荐
- javaScript【创建对象、创建类、成员变量、方法、公有和私有、静态】
创建对象 方式① 直接使用new Object() var obj = new Object(); 方式② 使用空的{}大括号 var obj2 = {}; 测试 增加属性,访问属性 我们要为创建的对 ...
- Struts2第十二篇【模型驱动】
什么是模型驱动 在Struts2中模型驱动就是用来封装数据的..完成数据的自动封装. 为什么要使用模型驱动? 我们之前就使用过Sturts2的数据自动封装功能,是用params拦截器完成的-既然有了p ...
- Eclipse中删除tomcat server 导致不能重新创建该版本的tomcat server
在Eclipse中创建了一个Web工程后,需要将该工程部署到Tomcat中进行发布.有时就会遇到在New Server对话框中选择了Tomcat 6/7后却无法单击“Next”按钮的问题,如下图所示: ...
- Java内存分配之堆、栈和常量池
Java内存分配主要包括以下几个区域: 1. 寄存器:我们在程序中无法控制 2. 栈:存放基本类型的数据和对象的引用,但对象本身不存放在栈中,而是存放在堆中 3. 堆:存放用new产生的数据 4. 静 ...
- pig hive hbase比较
Pig 一种操作hadoop的轻量级脚本语言,最初又雅虎公司推出,不过现在正在走下坡路了.当初雅虎自己慢慢退出pig的维护之后将它开源贡献到开源社区由所有爱好者来维护.不过现在还是有些公司在用,不过我 ...
- html5新特性与HTML的区别
* HTML5 现在已经不是 SGML 的子集,主要是关于图像,位置,存储,多任务等功能的增加. 绘画 canvas; 用于媒介回放的 video 和 audio 元素; 本地离线存储 localSt ...
- bzoj1051(明星奶牛)
这道就是明星奶牛,A了一次又一次了,(⊙o⊙)-(⊙o⊙)- 去年pas就打了不下5次,就是强联通缩点,然后求出度为0的块 判断有多个的话就无解,一个就输出块的大小. #include<cstd ...
- 项目发布Debug和Release版的区别
一.Debug和Release的区别 Debug:调试版本,包含调试信息,所以容量比Release大很多,并且不进行任何优化(优化会使调试复杂化,因为源代码和生成的指令间关系会更复杂),便于程序员调试 ...
- C-Flex 与 box布局教程
http://www.ruanyifeng.com/blog/2015/07/flex-grammar.html -阮一峰老师 http://www.w3cplus.com/css3/flexbox- ...
- webpack2使用ch1-目录说明
1 目录解释 webpack.config.js:配置文件,配置文件可以改成其他名,但package.json --config文件名称也要对应修改 2 webpack.config.js //we ...