var RandomizedSet = function() {
this.map = new Map(); // Map to store value and its index in the array
this.array = []; // Array to store values
};
/**
* @param {number} val
* @return {boolean}
*/
RandomizedSet.prototype.insert = function(val) {
if (this.map.has(val)) {
return false; // If val is already in the map, return false
}
// Otherwise, add val to the array and map
this.array.push(val);
this.map.set(val, this.array.length - 1);
return true;
};
/**
* @param {number} val
* @return {boolean}
*/
RandomizedSet.prototype.remove = function(val) {
if (!this.map.has(val)) {
return false; // If val is not in the map, return false
}
// Get the index of val in the array
let index = this.map.get(val);
let last = this.array[this.array.length - 1];
// If val is not the last value in the array, swap it with the last value
if (val !== last) {
this.array[index] = last;
this.map.set(last, index);
}
// Remove val from the array and map
this.array.pop();
this.map.delete(val);
return true;
};
/*
[1, 2, 3]
*/
/**
* @return {number}
*/
RandomizedSet.prototype.getRandom = function() {
// Get a random index between 0 and array.length - 1
let index = Math.floor(Math.random() * this.array.length);
return this.array[index];
};
/**
* 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()
*/