友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

380. Insert Delete GetRandom O(1)

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:

// 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();

思路分析

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
 * 自己实现
 */
class RandomizedSet {
  private List<Integer> nums;
  private Map<Integer, Integer> idex;
  private Random random;

  public RandomizedSet() {
    nums = new ArrayList<>();
    random = new Random();
    idex = new HashMap<>();
  }

  public boolean insert(int val) {
    if (idex.containsKey(val)) {
      return false;
    } else {
      nums.add(val);
      idex.put(val, nums.size() - 1);
      return true;
    }
  }

  public boolean remove(int val) {
    if (!idex.containsKey(val)) {
      return false;
    } else {
      int i1 = idex.get(val);
      if (i1 != idex.size() - 1) {
        Integer value = nums.get(nums.size() - 1);
        nums.set(i1, value);
        idex.put(value, i1);
      }
      idex.remove(val);
      nums.remove(nums.size() - 1);
      return true;
    }
  }

  public int getRandom() {
    return nums.get(random.nextInt(nums.size()));
  }
}