Skip to content

Commit 4dc4b5c

Browse files
authored
Update 380-insert-delete-getrandom-o1.js
1 parent 181767e commit 4dc4b5c

File tree

1 file changed

+30
-28
lines changed

1 file changed

+30
-28
lines changed

380-insert-delete-getrandom-o1.js

+30-28
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,53 @@
11
/**
22
* Initialize your data structure here.
33
*/
4-
const RandomizedSet = function() {
5-
this.data = []
6-
};
4+
const RandomizedSet = function () {
5+
this.map = new Map()
6+
this.array = []
7+
}
78

89
/**
9-
* Inserts a value to the set. Returns true if the set did not already contain the specified element.
10+
* Inserts a value to the set. Returns true if the set did not already contain the specified element.
1011
* @param {number} val
1112
* @return {boolean}
1213
*/
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-
};
14+
RandomizedSet.prototype.insert = function (val) {
15+
const { array, map } = this
16+
if (map.has(val)) return false
17+
array.push(val)
18+
map.set(val, array.length - 1)
19+
return true
20+
}
2021

2122
/**
22-
* Removes a value from the set. Returns true if the set contained the specified element.
23+
* Removes a value from the set. Returns true if the set contained the specified element.
2324
* @param {number} val
2425
* @return {boolean}
2526
*/
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-
};
27+
RandomizedSet.prototype.remove = function (val) {
28+
const { array, map } = this
29+
if (!map.has(val)) return false
30+
const [last, index] = [array[array.length - 1], map.get(val)]
31+
array[index] = last
32+
map.set(last, index)
33+
array.pop()
34+
map.delete(val)
35+
return true
36+
}
3537

3638
/**
3739
* Get a random element from the set.
3840
* @return {number}
3941
*/
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-
};
42+
RandomizedSet.prototype.getRandom = function () {
43+
const { array } = this
44+
const r = Math.floor(array.length * Math.random())
45+
return array[r]
46+
}
4547

46-
/**
48+
/**
4749
* Your RandomizedSet object will be instantiated and called as such:
48-
* var obj = Object.create(RandomizedSet).createNew()
50+
* var obj = new RandomizedSet()
4951
* var param_1 = obj.insert(val)
5052
* var param_2 = obj.remove(val)
5153
* var param_3 = obj.getRandom()

0 commit comments

Comments
 (0)