-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathh381.java
55 lines (47 loc) · 1.6 KB
/
h381.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
class RandomizedCollection {
private ArrayList<Integer> vals;
private HashMap<Integer, HashSet<Integer>> indices;
public RandomizedCollection() {
this.vals = new ArrayList<>();
this.indices = new HashMap<>();
}
public boolean insert(int val) {
if (!this.indices.containsKey(val)) {
this.indices.put(val, new HashSet<>());
}
this.indices.get(val).add(this.vals.size());
this.vals.add(val);
// If it wasn't present before, the new size will be 1
return this.indices.get(val).size() <= 1;
}
public boolean remove(int val) {
if (!this.indices.containsKey(val)) {
return false;
}
int indx = this.indices.get(val).iterator().next();
this.indices.get(val).remove(indx);
if (indx == vals.size() - 1) {
this.vals.removeLast();
} else {
int lastVal = this.vals.removeLast();
this.vals.set(indx, lastVal);
this.indices.get(lastVal).remove(this.vals.size());
this.indices.get(lastVal).add(indx);
}
// Cleanup
if (this.indices.get(val).size() == 0) {
this.indices.remove(val);
}
return true;
}
public int getRandom() {
return this.vals.get((int) (Math.random() * this.vals.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();
*/