-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertDeleteRandom.java
More file actions
41 lines (35 loc) · 1.15 KB
/
Copy pathInsertDeleteRandom.java
File metadata and controls
41 lines (35 loc) · 1.15 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
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Set;
public class InsertDeleteRandom {
ArrayList<Integer> lst;
HashMap<Integer, Set<Integer>> idx;
java.util.Random rand = new java.util.Random();
public void RandomizedCollection() {
lst = new ArrayList<Integer>();
idx = new HashMap<Integer, Set<Integer>>();
}
public boolean insert(int val) {
if (!idx.containsKey(val))
idx.put(val, new LinkedHashSet<Integer>());
idx.get(val).add(lst.size());
lst.add(val);
return idx.get(val).size() == 1;
}
public boolean remove(int val) {
if (!idx.containsKey(val) || idx.get(val).size() == 0)
return false;
int remove_idx = idx.get(val).iterator().next();
idx.get(val).remove(remove_idx);
int last = lst.get(lst.size() - 1);
lst.set(remove_idx, last);
idx.get(last).add(remove_idx);
idx.get(last).remove(lst.size() - 1);
lst.remove(lst.size() - 1);
return true;
}
public int getRandom() {
return lst.get(rand.nextInt(lst.size()));
}
}