-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path11.RandomizedSet.js
45 lines (41 loc) · 1.05 KB
/
11.RandomizedSet.js
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
var RandomizedSet = function() {
this.array = new Array()
this.map = new Map();
};
/**
* @param {number} val
* @return {boolean}
*/
RandomizedSet.prototype.insert = function(val) {
if(this.map.has(val)) return false;
this.map.set(val, this.array.length);
this.array.push(val);
return true;
};
/**
* @param {number} val
* @return {boolean}
*/
RandomizedSet.prototype.remove = function(val) {
if(!this.map.has(val)) return false;
const index = this.map.get(val);
this.array[index] = this.array[this.array.length-1];
this.map.set(this.array[index], index);
this.array.pop();
this.map.delete(val);
return true;
};
/**
* @return {number}
*/
RandomizedSet.prototype.getRandom = function() {
const randomindex = Math.floor(Math.random() * this.array.length);
return this.array[randomindex];
};
/**
* Your RandomizedSet object will be instantiated and called as such:
* var obj = new RandomizedSet()
* var param_1 = obj.insert(val)
* var param_2 = obj.remove(val)
* var param_3 = obj.getRandom()
*/