leetcode 380. O(1) 时间插入、删除和获取随机元素

一、题目地址

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()
 */

三、补充链接

https://leetcode-cn.com/problems/insert-delete-getrandom-o1/solution/jie-he-ha-xi-biao-he-shu-zu-de-te-xing-l-gyqc/

四、补充部分

关注公众号:【深漂程序员小庄】:
内含丰富的学习资源和面试经验(不限前端、java),还有学习交流群可加,并且还有各大厂大佬可一起交流学习,一起进步~添加小庄微信,回复【加群】,可加入互联网技术交流群:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值