-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathP_381.java
More file actions
55 lines (47 loc) · 1.47 KB
/
Copy pathP_381.java
File metadata and controls
55 lines (47 loc) · 1.47 KB
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
package leetcode.hard;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
public class P_381 {
public static class RandomizedCollection {
List<Integer> nums;
Map<Integer, Set<Integer>> map;
Random r;
public RandomizedCollection() {
nums = new ArrayList<>();
map = new HashMap<>();
r = new Random();
}
public boolean insert(int val) {
if (!map.containsKey(val)) {
map.put(val, new LinkedHashSet<>());
}
map.get(val).add(nums.size());
nums.add(val);
return true;
}
public boolean remove(int val) {
if (!map.containsKey(val)) {
return false;
}
final int currIdx = map.get(val).iterator().next();
map.get(val).remove(currIdx);
if (currIdx < nums.size() - 1) {
final int last = nums.get(nums.size() - 1);
nums.set(currIdx, last);
map.get(last).remove(nums.size() - 1);
map.get(last).add(currIdx);
}
nums.remove(nums.size() - 1);
if (map.get(val).isEmpty()) { map.remove(val); }
return true;
}
public int getRandom() {
return nums.get(r.nextInt(nums.size()));
}
}
}