-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy path380.java
More file actions
36 lines (31 loc) · 994 Bytes
/
380.java
File metadata and controls
36 lines (31 loc) · 994 Bytes
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
class RandomizedSet {
private Map<Integer, Integer> valueToIndex = new HashMap<>();
private List<Integer> valuesList = new ArrayList<>();
private Random rand = new Random();
private int getLastFromList(List<Integer> valuesList) {
return valuesList.get(valuesList.size()-1);
}
public boolean insert(int val) {
if(valueToIndex.containsKey(val)){
return false;
}
valueToIndex.put(val, valuesList.size());
valuesList.add(val);
return true;
}
public boolean remove(int val) {
if(!valueToIndex.containsKey(val)){
return false;
}
int index = valueToIndex.get(val);
valueToIndex.put(getLastFromList(valuesList), index);
valuesList.set(index, getLastFromList(valuesList));
valueToIndex.remove(val);
valuesList.remove(valuesList.size()-1);
return true;
}
public int getRandom() {
final int index = rand.nextInt(valuesList.size());
return valuesList.get(index);
}
}