Skip to content

Commit 6204a77

Browse files
authored
Create 380-insert-delete-getrandom-o1.js
1 parent a791b32 commit 6204a77

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

380-insert-delete-getrandom-o1.js

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* Initialize your data structure here.
3+
*/
4+
const RandomizedSet = function() {
5+
this.data = []
6+
};
7+
8+
/**
9+
* Inserts a value to the set. Returns true if the set did not already contain the specified element.
10+
* @param {number} val
11+
* @return {boolean}
12+
*/
13+
RandomizedSet.prototype.insert = function(val) {
14+
if(this.data.indexOf(val) === -1) {
15+
this.data.push(val)
16+
return true
17+
}
18+
return false
19+
};
20+
21+
/**
22+
* Removes a value from the set. Returns true if the set contained the specified element.
23+
* @param {number} val
24+
* @return {boolean}
25+
*/
26+
RandomizedSet.prototype.remove = function(val) {
27+
let idx = this.data.indexOf(val)
28+
if(idx !== -1) {
29+
this.data.splice(idx, 1)
30+
return true
31+
}
32+
return false
33+
34+
};
35+
36+
/**
37+
* Get a random element from the set.
38+
* @return {number}
39+
*/
40+
RandomizedSet.prototype.getRandom = function() {
41+
const len = this.data.length
42+
const idx = Math.floor(Math.random() * len)
43+
return this.data[idx]
44+
};
45+
46+
/**
47+
* Your RandomizedSet object will be instantiated and called as such:
48+
* var obj = Object.create(RandomizedSet).createNew()
49+
* var param_1 = obj.insert(val)
50+
* var param_2 = obj.remove(val)
51+
* var param_3 = obj.getRandom()
52+
*/

0 commit comments

Comments
 (0)