-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0381-insert-delete-getrandom-o1-duplicates-allowed.js
More file actions
57 lines (45 loc) · 1.66 KB
/
0381-insert-delete-getrandom-o1-duplicates-allowed.js
File metadata and controls
57 lines (45 loc) · 1.66 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
57
/**
* Insert Delete Getrandom O1 Duplicates Allowed
* Time Complexity: O(1)
* Space Complexity: O(N)
*/
var RandomizedCollection = function () {
this.elementArray = [];
this.elementToIndices = new Map();
};
RandomizedCollection.prototype.insert = function (valueEntry) {
let initialPresence = false;
if (!this.elementToIndices.has(valueEntry)) {
this.elementToIndices.set(valueEntry, new Set());
initialPresence = true;
}
let currentIndicesSet = this.elementToIndices.get(valueEntry);
currentIndicesSet.add(this.elementArray.length);
this.elementArray.push(valueEntry);
return initialPresence;
};
RandomizedCollection.prototype.remove = function (valueToRemove) {
if (!this.elementToIndices.has(valueToRemove)) {
return false;
}
let availableIndices = this.elementToIndices.get(valueToRemove);
let indexForRemoval = availableIndices.values().next().value;
let lastElementValue = this.elementArray[this.elementArray.length - 1];
let lastElementCurrentIndex = this.elementArray.length - 1;
availableIndices.delete(indexForRemoval);
if (indexForRemoval !== lastElementCurrentIndex) {
this.elementArray[indexForRemoval] = lastElementValue;
let lastElementIndices = this.elementToIndices.get(lastElementValue);
lastElementIndices.delete(lastElementCurrentIndex);
lastElementIndices.add(indexForRemoval);
}
this.elementArray.pop();
if (availableIndices.size === 0) {
this.elementToIndices.delete(valueToRemove);
}
return true;
};
RandomizedCollection.prototype.getRandom = function () {
let randomArrayIndex = Math.floor(Math.random() * this.elementArray.length);
return this.elementArray[randomArrayIndex];
};