LeetCode 381. O(1) 时间插入、删除和获取随机元素 - 允许重复 JAVA

川长思鸟来 2022-11-21 09:53 164阅读 0赞

设计一个支持在平均 时间复杂度 O(1) 下, 执行以下操作的数据结构。

注意: 允许出现重复元素。

insert(val):向集合中插入元素 val。
remove(val):当 val 存在时,从集合中移除一个 val。
getRandom:从现有集合中随机获取一个元素。每个元素被返回的概率应该与其在集合中的数量呈线性相关。

  1. 示例:
  2. // 初始化一个空的集合。
  3. RandomizedCollection collection = new RandomizedCollection();
  4. // 向集合中插入 1 。返回 true 表示集合不包含 1 。
  5. collection.insert(1);
  6. // 向集合中插入另一个 1 。返回 false 表示集合包含 1 。集合现在包含 [1,1] 。
  7. collection.insert(1);
  8. // 向集合中插入 2 ,返回 true 。集合现在包含 [1,1,2] 。
  9. collection.insert(2);
  10. // getRandom 应当有 2/3 的概率返回 1 ,1/3 的概率返回 2 。
  11. collection.getRandom();
  12. // 从集合中删除 1 ,返回 true 。集合现在包含 [1,2] 。
  13. collection.remove(1);
  14. // getRandom 应有相同概率返回 1 和 2 。
  15. collection.getRandom();
  16. 来源:力扣(LeetCode
  17. 链接:https://leetcode-cn.com/problems/insert-delete-getrandom-o1-duplicates-allowed
  18. 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
  19. class RandomizedCollection {
  20. List<Integer> list;
  21. Random r;
  22. /** Initialize your data structure here. */
  23. public RandomizedCollection() {
  24. list=new ArrayList<>();
  25. r=new Random();
  26. }
  27. /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
  28. public boolean insert(int val) {
  29. if(list.contains(val)){
  30. list.add(val);
  31. return false;
  32. }
  33. else {
  34. list.add(val);
  35. return true;
  36. }
  37. }
  38. /** Removes a value from the collection. Returns true if the collection contained the specified element. */
  39. public boolean remove(int val) {
  40. for(int i=0;i<list.size();i++){
  41. if(list.get(i)==val){
  42. list.remove(i);
  43. return true;
  44. }
  45. }
  46. return false;
  47. }
  48. /** Get a random element from the collection. */
  49. public int getRandom() {
  50. int index=r.nextInt(list.size());
  51. return list.get(index);
  52. }
  53. }
  54. /**
  55. * Your RandomizedCollection object will be instantiated and called as such:
  56. * RandomizedCollection obj = new RandomizedCollection();
  57. * boolean param_1 = obj.insert(val);
  58. * boolean param_2 = obj.remove(val);
  59. * int param_3 = obj.getRandom();
  60. */

发表评论

表情:
评论列表 (有 0 条评论,164人围观)

还没有评论,来说两句吧...

相关阅读