-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathInsert Delete GetRandom O(1).js
51 lines (47 loc) · 1.21 KB
/
Insert Delete GetRandom O(1).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
46
47
48
49
50
51
var RandomizedSet = function() {
this.ranArray = []
this.ranObj = {}
};
/**
* @param {number} val
* @return {boolean}
*/
RandomizedSet.prototype.insert = function(val) {
if (this.ranObj[val] === undefined) {
this.ranArray[this.ranArray.length] = val
this.ranObj[val] = this.ranArray.length - 1
return true
} else {
return false
}
};
/**
* @param {number} val
* @return {boolean}
*/
RandomizedSet.prototype.remove = function(val) {
if (this.ranObj[val] === undefined) {
return false
} else {
let tempLastVal = this.ranArray[this.ranArray.length - 1]
let tempRemoveIndex = this.ranObj[val]
this.ranObj[tempLastVal] = tempRemoveIndex
this.ranArray[tempRemoveIndex] = tempLastVal
this.ranArray.pop()
delete this.ranObj[val]
return true
}
};
/**
* @return {number}
*/
RandomizedSet.prototype.getRandom = function() {
return this.ranArray[Math.floor(Math.random()*this.ranArray.length)]
};
/**
* 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()
*/