-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRandomizedCollection.java
More file actions
56 lines (49 loc) · 1.31 KB
/
Copy pathRandomizedCollection.java
File metadata and controls
56 lines (49 loc) · 1.31 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
56
import java.util.*;
public class RandomizedCollection
{
List<Integer> list;
Map<Integer, HashSet<Integer>> indices;
Random rand = new Random();
public RandomizedCollection()
{
list = new ArrayList<Integer>();
indices = new HashMap<Integer, HashSet<Integer>>();
}
public boolean insert(int val)
{
boolean duplicate = indices.containsKey(val);
indices.putIfAbsent(val, new LinkedHashSet<>());
indices.get(val).add(list.size());
list.add(val);
return !duplicate;
}
public boolean remove(int val)
{
if (!indices.containsKey(val))
{
return false;
}
int idx = indices.get(val).iterator().next();
indices.get(val).remove(idx);
if (idx < list.size() - 1)
{
int replaceVal = list.get(list.size() - 1);
list.set(idx, replaceVal);
indices.get(replaceVal).remove(list.size() - 1);
indices.get(replaceVal).add(idx);
}
list.remove(list.size() - 1);
if (indices.get(val).isEmpty())
{
indices.remove(val);
}
return true;
}
/**
* Get a random element from the set.
*/
public int getRandom()
{
return list.get(rand.nextInt(list.size()));
}
}