echo

任生命穿梭 时间的角落

0%

时间插入、删除和获取随机元素-允许重复

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

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

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

  1. insert(val):向集合中插入元素 val。

  2. remove(val):当 val 存在时,从集合中移除一个 val。

  3. getRandom:从现有集合中随机获取一个元素。每个元素被返回的概率应该与其在集合中的数量呈线性相关。

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 初始化一个空的集合。
RandomizedCollection collection = new RandomizedCollection();

// 向集合中插入 1 。返回 true 表示集合不包含 1 。
collection.insert(1);

// 向集合中插入另一个 1 。返回 false 表示集合包含 1 。集合现在包含 [1,1] 。
collection.insert(1);

// 向集合中插入 2 ,返回 true 。集合现在包含 [1,1,2] 。
collection.insert(2);

// getRandom 应当有 2/3 的概率返回 1 ,1/3 的概率返回 2 。
collection.getRandom();

// 从集合中删除 1 ,返回 true 。集合现在包含 [1,2] 。
collection.remove(1);

// getRandom 应有相同概率返回 1 和 2 。
collection.getRandom();

使用一个数组 nums 存储所有的数字,我们随机生成下标就可在 O(1)时间内得到一个随机元素。

在列表中删除最后一个元素的时间复杂度是 O(1),如果要在 O(1)时间复杂度删除数组中间的元素,我们需要将它与最后一个元素交换,最后将最后一个元素删除。

remove 函数的参数为删除的数的 val,我们需要将一个数值对应数组中的下标存储起来,使用一个Set 存储。

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

class RandomizedCollection {

Map<Integer, Set<Integer>> map;
List<Integer> nums;
/** Initialize your data structure here. */
public RandomizedCollection() {
map = new HashMap<Integer, Set<Integer>>();
nums = new ArrayList<Integer>();
}

/** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
public boolean insert(int val) {
//将 val 添加到数组中
nums.add(val);
//将 当前下标添加进 val 对应的 set
Set<Integer> set = map.getOrDefault(val, new HashSet<Integer>());
set.add(nums.size() - 1);
//将 set 放入 map
map.put(val, set);
//数组中是否已经存在 val
return set.size() == 1;
}

/** Removes a value from the collection. Returns true if the collection contained the specified element. */
public boolean remove(int val) {
//数组中没有 val,删除失败
if(!map.containsKey(val)){
return false;
}
//得到 val 对应的一个 数组下标
Iterator<Integer> it = map.get(val).iterator();
int i = it.next();
//得到数组中最后一个数字
int lastNum = nums.get(nums.size() - 1);
//将最后一个数组拷贝到下标 i 处
nums.set(i, lastNum);

//删除set 中的下标
map.get(val).remove(i);
map.get(lastNum).remove(nums.size() - 1);
//将 lastNum 的新下标加入set
if(i < nums.size() - 1){
map.get(lastNum).add(i);
}
//删除后 set 为空,删除这个 键值对
if(map.get(val).size() == 0){
map.remove(val);
}
//删除数组中最后一个元素
nums.remove(nums.size() - 1);
return true;
}

/** Get a random element from the collection. */
public int getRandom() {
//随机生成数组下标
return nums.get( (int) ( Math.random() * nums.size() ) );
}
}
  • 时间复杂度O(1)
  • 空间复杂度O(N),N为数组中所有元素的数目。