【Leetcode】 381. Insert Delete GetRandom O(1) - Duplicates allowed

Description

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

Note

Duplicate elements are allowed.
insert(val): Inserts an item val to the collection.
remove(val): Removes an item val from the collection if present.
getRandom: Returns a random element from current collection of elements. The probability of each element being returned is linearly related to the number of same value the collection contains.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Init an empty collection.
RandomizedCollection collection = new RandomizedCollection();
// Inserts 1 to the collection. Returns true as the collection did not contain 1.
collection.insert(1);
// Inserts another 1 to the collection. Returns false as the collection contained 1. Collection now contains [1,1].
collection.insert(1);
// Inserts 2 to the collection, returns true. Collection now contains [1,1,2].
collection.insert(2);
// getRandom should return 1 with the probability 2/3, and returns 2 with the probability 1/3.
collection.getRandom();
// Removes 1 from the collection, returns true. Collection now contains [1,2].
collection.remove(1);
// getRandom should return 1 and 2 both equally likely.
collection.getRandom();

Solution

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
public class RandomizedCollection {
List<Integer> nums;
HashMap<Integer, Set<Integer>> map;
java.util.Random rand = new java.util.Random();
public RandomizedCollection() {
nums = new ArrayList<>();
map = new HashMap<>();
}
public boolean insert(int val) {
boolean contain = map.containsKey(val);
if (!contain) {
map.put(val, new LinkedHashSet<>());
}
map.get(val).add(nums.size());
nums.add(val);
return !contain;
}
public boolean remove(int val) {
boolean contain = map.containsKey(val);
if (!contain) {
return false;
}
int index = map.get(val).iterator().next();
map.get(val).remove(index);
if (index < nums.size() - 1) {
int lastone = nums.get(nums.size() - 1);
map.get(lastone).remove(nums.size() - 1);
map.get(lastone).add(index);
nums.set(index, lastone);
}
nums.remove(nums.size() - 1);
if (map.get(val).size() == 0) {
map.remove(val);
}
return true;
}
public int getRandom() {
return nums.get(rand.nextInt(nums.size()));
}
}

Analyse

这道题很值得细细思考,首先,为什么要用LinkedHashSet,而不是普通的set,因为HashSet不能保证插入的顺序,LinkedHashSet可以按照插入的顺序来对数据进行操作。至于为什么要保持顺序,那就是和nums对应,打一个简单的比方。

1
2
3
4
5
6
7
8
9
10
11
12
//map 0 <1>, 1 <1, 2>, 2 <3, 4>
//nums {0, 1, 1, 2, 2>
//remove 1之后,后续的格式为
//map 0 <1>, 1 <2>, 2 <3, 1>
//nums {0, 2, 1, 2}
//这样数字对应的index和map里的数字的LinkedHashSet是一样的。
//为什么需要对应一样,那接下来看
//要是remove2很直观,如果接下来remove1
//map 0 <1>, 1 <>, 2 <3, 1>
//这样接下来操作
//map 0 <1>, 1 <>, 2 <2, 1>
//一套技能下来,对数据结构的理解也更深

坚持原创技术分享,您的支持将鼓励我继续创作!