forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInsert Delete GetRandom O(1) - Duplicates allowed.java
49 lines (43 loc) · 1.39 KB
/
Insert Delete GetRandom O(1) - 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
class RandomizedCollection {
List<Integer> multiSet;
HashMap<Integer, PriorityQueue<Integer>> map;
Random random;
public RandomizedCollection() {
map = new HashMap<>();
multiSet = new ArrayList<>();
random = new Random();
}
public boolean insert(int val) {
boolean contains = map.containsKey(val);
multiSet.add(val);
PriorityQueue<Integer> pq;
if(!contains){
pq = new PriorityQueue<>(Collections.reverseOrder());
map.put(val, pq);
}else
pq = map.get(val);
pq.add(multiSet.size()-1);
return !contains;
}
public boolean remove(int val) {
if(!map.containsKey(val))
return false;
PriorityQueue<Integer> pq = map.get(val);
int indexToRemove = pq.poll();
if(pq.size() == 0) map.remove(val);
int lastIndex = multiSet.size()-1;
if(indexToRemove != lastIndex){
int valLast = multiSet.get(lastIndex);
PriorityQueue<Integer> temp = map.get(valLast);
temp.poll();
temp.add(indexToRemove);
multiSet.set(indexToRemove, valLast);
}
multiSet.remove(lastIndex);
return true;
}
public int getRandom() {
int index = random.nextInt(multiSet.size());
return multiSet.get(index);
}
}