|
1 | 1 | /**
|
2 | 2 | * Initialize your data structure here.
|
3 | 3 | */
|
4 |
| -const RandomizedSet = function() { |
5 |
| - this.data = [] |
6 |
| -}; |
| 4 | +const RandomizedSet = function () { |
| 5 | + this.map = new Map() |
| 6 | + this.array = [] |
| 7 | +} |
7 | 8 |
|
8 | 9 | /**
|
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. |
10 | 11 | * @param {number} val
|
11 | 12 | * @return {boolean}
|
12 | 13 | */
|
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 | +} |
20 | 21 |
|
21 | 22 | /**
|
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. |
23 | 24 | * @param {number} val
|
24 | 25 | * @return {boolean}
|
25 | 26 | */
|
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 | +} |
35 | 37 |
|
36 | 38 | /**
|
37 | 39 | * Get a random element from the set.
|
38 | 40 | * @return {number}
|
39 | 41 | */
|
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 | +} |
45 | 47 |
|
46 |
| -/** |
| 48 | +/** |
47 | 49 | * Your RandomizedSet object will be instantiated and called as such:
|
48 |
| - * var obj = Object.create(RandomizedSet).createNew() |
| 50 | + * var obj = new RandomizedSet() |
49 | 51 | * var param_1 = obj.insert(val)
|
50 | 52 | * var param_2 = obj.remove(val)
|
51 | 53 | * var param_3 = obj.getRandom()
|
|
0 commit comments