当前位置: 首页 > article >正文

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

实现RandomizedSet 类:

RandomizedSet() 初始化 RandomizedSet 对象
bool insert(int val) 当元素 val 不存在时,向集合中插入该项,并返回 true ;否则,返回 false 。
bool remove(int val) 当元素 val 存在时,从集合中移除该项,并返回 true ;否则,返回 false 。
int getRandom() 随机返回现有集合中的一项(测试用例保证调用此方法时集合中至少存在一个元素)。每个元素应该有 相同的概率 被返回。
你必须实现类的所有函数,并满足每个函数的 平均 时间复杂度为 O(1) 。

示例:

输入
[“RandomizedSet”, “insert”, “remove”, “insert”, “getRandom”, “remove”, “insert”, “getRandom”]
[[], [1], [2], [2], [], [1], [2], []]
输出
[null, true, false, true, 2, true, false, 2]

解释
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // 向集合中插入 1 。返回 true 表示 1 被成功地插入。
randomizedSet.remove(2); // 返回 false ,表示集合中不存在 2 。
randomizedSet.insert(2); // 向集合中插入 2 。返回 true 。集合现在包含 [1,2] 。
randomizedSet.getRandom(); // getRandom 应随机返回 1 或 2 。
randomizedSet.remove(1); // 从集合中移除 1 ,返回 true 。集合现在包含 [2] 。
randomizedSet.insert(2); // 2 已在集合中,所以返回 false 。
randomizedSet.getRandom(); // 由于 2 是集合中唯一的数字,getRandom 总是返回 2 。

解法:

    const RandomizedSet = function () {
        this.nums = [];
        this.randomMap = {};
    }

    /**
     * @param {number} val
     * @return {boolean}
     */
    RandomizedSet.prototype.insert = function(val) {
        if (this.randomMap[val]){
            return false
        }
        this.nums.push(val);
        this.randomMap[val] = this.nums.length
        return true
    };

    /**
     * @param {number} val
     * @return {boolean}
     */
    RandomizedSet.prototype.remove = function(val) {
        if (!this.randomMap[val]){
            return false
        }
        const index = this.nums.findIndex(t=>t===val);
        this.nums.splice(index,1);
        delete this.randomMap[val]
        return true
    };

    /**
     * @return {number}
     */
    RandomizedSet.prototype.getRandom = function() {
        const index = Math.floor(Math.random()*this.nums.length);
        return this.nums[index]
    };

http://www.kler.cn/news/109026.html

相关文章:

  • 你会处理 go 中的 nil 吗
  • ChatGPT 驱动软件开发:AI 在软件研发全流程中的革新与实践
  • 38基于matlab的期货预测,利用PSO优化SVM和未优化的SVM进行对比,得到实际输出和期望输出结果。
  • 万字解析设计模式之单例模式
  • 为wget命令设置代理
  • 利用 JSqlParser 防止 SQL 注入
  • String、StringBuffer、StringBuilder和StringJoiner
  • prometheus服务发现
  • 松下A6B伺服 马达不动问题解决
  • Photoshop(PS)2021版 安装教程(图文教程超详细)
  • git建仓库小记
  • C#__简单了解XML文档
  • 谈谈我对 Reacitive 方法的理解
  • Java开发中方法命名规范
  • NCCL后端
  • 面试测试工程师一般问什么问题?
  • 【Java】选择语句、循环语句
  • Mybatisplus 常用注解
  • Elasticsearch跨集群检索配置
  • Linux C/C++ 实现网络流量分析(性能工具)
  • 海外问卷调查是怎么做的?全方位介绍!
  • 【Git】HEAD detached from xxx 问题及解决方案
  • Hive创建分区表并插入数据
  • bat文件学习
  • 基于STM32的示波器信号发生器设计
  • LeetCode 917 仅仅反转字母 简单
  • GnuTLS recv error (-110): The TLS connection was non-properly terminated
  • C#学习相关系列之多线程(七)---Task的相关属性用法
  • 算法训练|数据流中的中位数
  • Visual Studio Code的下载与安装