/** * Initialize your data structure here. */ varRandomizedSet = function() { this.set = []; this.map = {}; };
/** * Inserts a value to the set. Returns true if the set did not already contain the specified element. * @param {number} val * @return {boolean} */ RandomizedSet.prototype.insert = function(val) { if(val inthis.map){ returnfalse; } this.set.push(val); this.map[val] = this.set.length - 1; returntrue; };
/** * Removes a value from the set. Returns true if the set contained the specified element. * @param {number} val * @return {boolean} */ RandomizedSet.prototype.remove = function(val) { if(!(val inthis.map)){ returnfalse; } let last = this.set.pop(); let index = this.map[val]; deletethis.map[val]; if(val !== last){ this.set[index] = last; this.map[last] = index; } returntrue; };
/** * Get a random element from the set. * @return {number} */ RandomizedSet.prototype.getRandom = function() { let rand = Math.floor(Math.random() * this.set.length); returnthis.set[rand] };
/** * 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() */