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:

  1. // Init an empty set.
  2. RandomizedSet randomSet = new RandomizedSet();
  3.  
  4. // Inserts 1 to the set. Returns true as 1 was inserted successfully.
  5. randomSet.insert(1);
  6.  
  7. // Returns false as 2 does not exist in the set.
  8. randomSet.remove(2);
  9.  
  10. // Inserts 2 to the set, returns true. Set now contains [1,2].
  11. randomSet.insert(2);
  12.  
  13. // getRandom should return either 1 or 2 randomly.
  14. randomSet.getRandom();
  15.  
  16. // Removes 1 from the set, returns true. Set now contains [2].
  17. randomSet.remove(1);
  18.  
  19. // 2 was already in the set, so return false.
  20. randomSet.insert(2);
  21.  
  22. // Since 2 is the only number in the set, getRandom always return 2.
  23. randomSet.getRandom();
  1.  
  1. class RandomizedSet {
  2.  
  3. private Map<Integer, Integer> map;
  4. private List<Integer> list;
  5. private Random rand;
  6. /** Initialize your data structure here. */
  7. public RandomizedSet() {
  8. map = new HashMap<>();
  9. list = new ArrayList<>();
  10. rand = new Random();
  11. }
  12.  
  13. /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
  14. public boolean insert(int val) {
  15. if (map.containsKey(val)) {
  16. return false;
  17. }
  18. map.put(val, list.size());
  19. list.add(val);
  20. return true;
  21. }
  22.  
  23. /** Removes a value from the set. Returns true if the set contained the specified element. */
  24. public boolean remove(int val) {
  25. if (!map.containsKey(val)) {
  26. return false;
  27. }
  28. int index = map.remove(val);
  29. int lastValue = list.remove(list.size() - 1);
  30. if (val != lastValue) {
  31. // need to fill back the removal list index
  32. list.set(index, lastValue);
  33. map.put(lastValue, index);
  34. }
  35. return true;
  36. }
  37.  
  38. /** Get a random element from the set. */
  39. public int getRandom() {
  40. return list.get(rand.nextInt(list.size()));
  41. }
  42. }
  43.  
  44. /**
  45. * Your RandomizedSet object will be instantiated and called as such:
  46. * RandomizedSet obj = new RandomizedSet();
  47. * boolean param_1 = obj.insert(val);
  48. * boolean param_2 = obj.remove(val);
  49. * int param_3 = obj.getRandom();
  50. */

[LC] 380. Insert Delete GetRandom 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) 解题报告(Python)

    [LeetCode]380. Insert Delete GetRandom O(1) 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxu ...

  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) 插入删除获得随机数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)常数时间插入删除取随机值

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

  7. 380. Insert Delete GetRandom O(1) 设计数据结构:在1的时间内插入、删除、产生随机数

    [抄题]: Design a data structure that supports all following operations in average O(1) time. insert(va ...

  8. LeetCode 380. Insert Delete GetRandom O(1) (插入删除和获得随机数 常数时间)

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

  9. LeetCode 380. Insert Delete GetRandom O(1) 常数时间插入、删除和获取随机元素(C++/Java)

    题目: Design a data structure that supports all following operations in averageO(1) time. insert(val): ...

随机推荐

  1. 解决 urxvt “unknown terminal type.”

    登录到远程服务器上后,有时执行某些命令会提示unknown terminal type. 这是因为远程ssh不支持urxvt,执行 export TERM=xterm-256color 或者在远程主机 ...

  2. 面试准备 css 书写顺序及原理

    书写顺序 (1)定位属性:position  display  float  left  top  right  bottom   overflow  clear   z-index (2)自身属性: ...

  3. 小程序Java多次请求Session不变

    微信小程序每次请求的sessionid是变化的,导致对应后台的session不一致,无法获取之前保存在session中的openid和sessionKey. 为了解决这个问题,需要强制同意每次小程序前 ...

  4. PAT Basic 1043 输出PATest (20分)[Hash散列]

    题目 给定⼀个⻓度不超过10000的.仅由英⽂字⺟构成的字符串.请将字符重新调整顺序,按"PATestPATest-."这样的顺序输出,并忽略其它字符.当然,六种字符的个数不⼀定是 ...

  5. Scrapy连接到各类数据库(SQLite,Mysql,Mongodb,Redis)

    如何使用scrapy连接到(SQLite,Mysql,Mongodb,Redis)数据库,并把爬取的数据存储到相应的数据库中. 一.SQLite 1.修改pipelines.py文件加入如下代码 # ...

  6. TT(Tokyo Tyrant )介绍及使用

    Tokyo Cabinet 是日本人 平林幹雄 开发的一款 DBM 数据库,该数据库读写非常快,哈希模式写入100万条数据只需0.643秒,读取100万条数据只需0.773秒,是 Berkeley D ...

  7. Angular(三)

    Angular开发者指南(三)数据绑定   数据绑定AngularJS应用程序中的数据绑定是模型和视图组件之间的数据的自动同步. AngularJS实现数据绑定的方式可以将模型视为应用程序中的单一来源 ...

  8. DevComponents.DotNetBar2.dll设置样式的使用

    有点模仿QQ消息盒子的感觉,代码如下: using System; using System.Collections.Generic; using System.ComponentModel; usi ...

  9. 理解python的可变参数

    以 str.format(*args,**kwargs) 为例. "type1:{},{},{},{}_type2:{a},{b},{c},{d}".format('a',2,*[ ...

  10. shell并行处理

    for i in (file1 file2 file3), do process_a $i | tee process_a $i_a.txt | process_b > $i_b.txt &am ...