-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinsert-delete-getrandom-o1-duplicates-allowed.java
66 lines (52 loc) · 1.69 KB
/
insert-delete-getrandom-o1-duplicates-allowed.java
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
61
62
63
64
65
66
// Problem link - https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/
class RandomizedCollection {
List<Integer> nums;
Map<Integer, Set<Integer>> idxMap;
Random random;
public RandomizedCollection() {
nums = new ArrayList<>();
idxMap = new HashMap<>();
random = new Random();
}
public boolean insert(int val) {
boolean doesntContain = !idxMap.containsKey(val);
if(doesntContain){
idxMap.put(val, new HashSet<>());
}
idxMap.get(val).add(nums.size());
nums.add(val);
return doesntContain;
}
public boolean remove(int val) {
if(!idxMap.containsKey(val)){
return false;
}
Set<Integer> idxSet = idxMap.get(val);
int idxToBeRemoved = idxSet.iterator().next();
if(idxSet.size() == 1){
idxMap.remove(val);
} else {
idxSet.remove(idxToBeRemoved);
}
int lastIdx = nums.size() - 1;
if(idxToBeRemoved != lastIdx){
int lastVal = nums.get(lastIdx);
Set<Integer> lastIdxSet = idxMap.get(lastVal);
lastIdxSet.add(idxToBeRemoved);
lastIdxSet.remove(lastIdx);
nums.set(idxToBeRemoved, lastVal);
}
nums.remove(lastIdx);
return true;
}
public int getRandom() {
return nums.get(random.nextInt(nums.size()));
}
}
/**
* Your RandomizedCollection object will be instantiated and called as such:
* RandomizedCollection obj = new RandomizedCollection();
* boolean param_1 = obj.insert(val);
* boolean param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/