一、题目地址
https://leetcode-cn.com/problems/insert-delete-getrandom-o1/
二、具体代码
/**
* Initialize your data structure here.
*/
var RandomizedSet = function() {
this.map = new Map();
this.nums = [];
};
/**
* 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(this.map.has(val)) {
return false;
}
this.nums.push(val);
this.map.set(val, this.nums.length - 1);
return true;
};
/**
* 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(!this.map.has(val)) {
return false;
}
let location = this.map.get(val);
this.map.set(this.nums[this.nums.length - 1], location);
this.map.delete(val);
this.nums[location] = this.nums[this.nums.length - 1];
this.nums.length--;
return true;
};
/**
* Get a random element from the set.
* @return {number}
*/
RandomizedSet.prototype.getRandom = function() {
let index = parseInt(Math.random() * this.nums.length);
return this.nums[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()
*/
三、补充链接
四、补充部分
关注公众号:【深漂程序员小庄】:
内含丰富的学习资源和面试经验(不限前端、java),还有学习交流群可加,并且还有各大厂大佬可一起交流学习,一起进步~添加小庄微信,回复【加群】,可加入互联网技术交流群: