-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0380-insert-delete-getrandom-o1.js
More file actions
42 lines (35 loc) · 1.11 KB
/
0380-insert-delete-getrandom-o1.js
File metadata and controls
42 lines (35 loc) · 1.11 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
/**
* Insert Delete Getrandom O1
* Time Complexity: O(1)
* Space Complexity: O(N)
*/
var RandomizedSet = function () {
this.valueToIndexMap = new Map();
this.elementList = [];
};
RandomizedSet.prototype.insert = function (val) {
if (this.valueToIndexMap.has(val)) {
return false;
}
this.elementList.push(val);
let newIndexPosition = this.elementList.length - 1;
this.valueToIndexMap.set(val, newIndexPosition);
return true;
};
RandomizedSet.prototype.remove = function (val) {
if (!this.valueToIndexMap.has(val)) {
return false;
}
let indexOfElementToRemove = this.valueToIndexMap.get(val);
let lastElementValue = this.elementList[this.elementList.length - 1];
this.elementList[indexOfElementToRemove] = lastElementValue;
this.valueToIndexMap.set(lastElementValue, indexOfElementToRemove);
this.elementList.pop();
this.valueToIndexMap.delete(val);
return true;
};
RandomizedSet.prototype.getRandom = function () {
let currentSetSize = this.elementList.length;
let randomChosenIndex = Math.floor(Math.random() * currentSetSize);
return this.elementList[randomChosenIndex];
};