-
Notifications
You must be signed in to change notification settings - Fork 2
/
InsertDeleteGetRandomDuplicatesAllowed.java
76 lines (66 loc) · 1.75 KB
/
InsertDeleteGetRandomDuplicatesAllowed.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
67
68
69
70
71
72
73
74
75
76
package com.algorithm.playground.leetcode.problems.lc300.lc381;
import java.util.*;
/**
* https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/description/
*/
public class InsertDeleteGetRandomDuplicatesAllowed {
class RandomizedCollection {
private List<Integer> values = new ArrayList<>();
private Random rnd = new Random();
private Map<Integer, Set<Integer>> positions = new HashMap<>();
/**
* Initialize your data structure here.
*/
public RandomizedCollection() {
}
/**
* Inserts a value to the collection. Returns true if the collection did not already contain the specified element.
*/
public boolean insert(int val) {
boolean contains = positions.containsKey(val);
values.add(val);
int idx = values.size() - 1;
if (!contains) {
positions.put(val, new HashSet<>());
}
positions.get(val).add(idx);
return !contains;
}
/**
* Removes a value from the collection. Returns true if the collection contained the specified element.
*/
public boolean remove(int val) {
Set<Integer> list = positions.get(val);
if (list == null) {
return false;
}
int idx = list.iterator().next();
list.remove(idx);
int lastIdx = values.size() - 1;
if (idx < lastIdx) {
int lastVal = values.get(lastIdx);
Set<Integer> set = positions.get(lastVal);
set.remove(lastIdx);
set.add(idx);
values.set(idx, lastVal);
values.remove(lastIdx);
} else {
values.remove(lastIdx);
}
if (list.isEmpty()) {
positions.remove(val);
}
return true;
}
/**
* Get a random element from the collection.
*/
public int getRandom() {
if (values.isEmpty()) {
return 0;
}
int idx = rnd.nextInt(values.size());
return values.get(idx);
}
}
}