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

最先想到是用double LinkedList+Map, 没必要,arraylist+map就够了;另外取random的方法还有,rand.nextInt(int n) returns an integer in the range [0, n)

java.util.Random rand = new java.util.Random();

return nums.get( rand.nextInt(nums.size()) );

 public class RandomizedSet {
HashMap<Integer, Integer> map;
ArrayList<Integer> arr; /** Initialize your data structure here. */
public RandomizedSet() {
map = new HashMap<Integer, Integer>();
arr = new ArrayList<Integer>();
} /** 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;
arr.add(val);
map.put(val, arr.size()-1);
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 lastItem = arr.get(arr.size()-1);
if (val != lastItem) {
int index = map.get(val);
arr.set(index, lastItem);
map.put(lastItem, index);
}
arr.remove(arr.size()-1);
map.remove(val);
return true;
} /** Get a random element from the set. */
public int getRandom() {
return arr.get((int)(Math.random()*arr.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: Insert Delete GetRandom O(1)的更多相关文章

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

    Design a data structure that supports all following operations in average O(1) time. Note: Duplicate ...

  2. [LeetCode] Insert Delete GetRandom O(1) 常数时间内插入删除和获得随机数

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

  3. Leetcode: Insert Delete GetRandom O(1) - Duplicates allowed

    Design a data structure that supports all following operations in average O(1) time. Note: Duplicate ...

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

  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) 插入删除获得随机数O(1)时间

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

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

  8. LeetCode 381. Insert Delete GetRandom O(1) - Duplicates allowed

    原题链接在这里:https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/?tab=Description ...

  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. Cacti安装详细步骤

    原文链接: https://www.centos.bz/2012/01/cacti-install-tutorials/ Cacti-监控MySQL: http://www.cszhi.com/201 ...

  2. composer autoload

    1.引入autoload 文件 include “vendor/autoload.php” 2.自定义的单文件引入 “autoload”:{ "files":["lib/ ...

  3. Machine Learning in Action -- 树回归

    前面介绍线性回归,但实际中,用线性回归去拟合整个数据集是不太现实的,现实中的数据往往不是全局线性的 当然前面也介绍了局部加权线性回归,这种方法有些局限 这里介绍另外一种思路,树回归 基本思路,用决策树 ...

  4. ecshop insert用法

    1 {insert name='ads' id=$ads_id num=$ads_num} 控制语句是在 /includes/lib_insert.php 文件.这个文件是ecshop动态内容函数库. ...

  5. sort,ksort,asort的区别

    sort--对数组的val进行排序 ksort--对数组的key值进行排序 asort--对数组进行排序,键与值的对应关系不变 1.sort对数组排序 格式如下:bool sort(array &am ...

  6. php--rbac权限

  7. php练习:给指定商品添加特殊效果

    老板说: 我只要在文本框填1|3 ,那第1和第3个商品都要标注! 思考过程: 有了重要信息1和3,而循环商品时$key按顺序自动递增,那么只要key和信息匹配的话,就判断商品添加标注,这个可以把位置信 ...

  8. Express创建并运行node项目(Jade和EJS模版引擎)

    1.创建Node项目 [Jade模板] > express nodeJade express创建项目若不显示指定模板,默认使用Jade,以下写法都可以: express -jade nodeJa ...

  9. String 与StringBuffer比较

    package String比较; /* * String 与StringBuffer比较 * String 不可变,一旦赋值,就不能被修改 * StringBuffer可变的字符串. * Strin ...

  10. iOS 给UILabel文字加下划线

    摘自:http://blog.sina.com.cn/s/blog_6cd380c10101b6hn.html //带下划线的“注” NSMutableAttributedString可变的属性字符串 ...