LeetCode 380. Insert Delete GetRandom O(1)(Medium)

Python自然语言处理 NLTK 库用法入门教程【经典】 @本文来源于公众号:csdn2299,喜欢可以关注公众号 程序员学府 本文实例讲述了Python自然语言处理 NLTK 库用法。分享给大家供大家参考,具体如下: 在这篇文章中,我们将基于 Python 讨论自然语言处理(NLP)。本教程将会使用 Python NLTK 库。NLTK 是一个当下流行的,用于自然语言处理的 Python 库。 那么 NLP 到底是什么?学习 NLP 能带来什么好处? ... 阅读详情

查阅更多的题解,请点击

Problem

380. Insert Delete GetRandom O(1)(Medium)

Design a data structure that supports all following operations in average O(1) time.

  1. insert(val): Inserts an item val to the set if not already present.
  2. remove(val): Removes an item val from the set if present.
  3. getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.

Example:

// Init an empty set.
RandomizedSet randomSet = new RandomizedSet();

// Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomSet.insert(1);

// Returns false as 2 does not exist in the set.
randomSet.remove(2);

// Inserts 2 to the set, returns true. Set now contains [1,2].
randomSet.insert(2);

// getRandom should return either 1 or 2 randomly.
randomSet.getRandom();

// Removes 1 from the set, returns true. Set now contains [2].
randomSet.remove(1);

// 2 was already in the set, so return false.
randomSet.insert(2);

// Since 2 is the only number in the set, getRandom always return 2.
randomSet.getRandom();

Solution

题意为设计一种数据结构,可以支持在平均O(1)时间复杂度的插入、删除、随机取一个元素的操作。

注意在题目要求的insert操作中,隐含了要求该数据结构能O(1)时间的查找。对于常见的数据结构:能做到O(1) time insert(), search(), delete()的只有hashTable.

此时还剩下getRandom()的实现,对于随机,直观地想到的是随机数,可以在O(1)的时间产生一个随机数,那么考虑如何将O(1)时间的访问和该随机数联系起来。可以用数字访问元素的数据结构为数组(下标访问)或者字典<key,value>的形式(key为数字)。

比较简单的做法是利用c++的unordered_set和vector实现符合题目要求的数据结构

class RandomizedSet
{
  private:
    unordered_set<int> set;
    vector<int> vec;
    std::default_random_engine generator;
    std::uniform_int_distribution<int> distribution;

  public:
    /** Initialize your data structure here. */
    RandomizedSet():distribution(0, INT_MAX)
    {
    }

    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    bool insert(int val)
    {
        if (set.find(val) != set.end())
            return false;
        set.insert(val);
        vec.emplace_back(val);
        return true;
    }

    /** Removes a value from the set. Returns true if the set contained the specified element. */
    bool remove(int val)
    {
        if (set.find(val) != set.end())
        {
            set.erase(val);
            return true;
        }
        return false;
    }

    /** Get a random element from the set. */
    int getRandom()
    {

        int val = 0;
        int n = vec.size();
        do
        {
            val = vec[distribution(generator) % n];
        } while (set.find(val) == set.end());
        return val;
    }
};

在上述代码中,存在一个问题,vector插入元素后不再删除,而hashset中的元素可能已被删除,所以需要下述操作来当前访问的元素是否存在

    int val = 0;
    int n = vec.size();
    do
    {
        val = vec[distribution(generator) % n];
    } while (set.find(val) == set.end());

考虑对这一过程进行优化,这里有一个很有用的编程技巧:当元素顺序无关紧要时,可以在O(1)的时间删除一个数组中的某个元素:

对于 0 1 2 3 4 5 6,尝试删除3,可以将3与6交换位置,再删除数组最后一个元素,整个算法过程如下(需要hashTable,可以在O(1)时间得到一个元素的位置):

  1. 如果您要删除的元素是向量中的最后一个元素,请将其删除,完成。
  2. 读取向量的最后一个元素,并将其写入要删除的元素。
  3. 删除向量的最后一个元素

GitHub传送门

class RandomizedSet
{
  private:
    unordered_map<int, int> map;
    vector<int> vec;
    std::default_random_engine generator;

  public:
    /** Initialize your data structure here. */
    RandomizedSet()
    {
    }

    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    bool insert(int val)
    {
        if (map.find(val) != map.end())
            return false;
        vec.emplace_back(val);
        map[val] = vec.size() - 1;
        return true;
    }

    /** Removes a value from the set. Returns true if the set contained the specified element. */
    bool remove(int val)
    {
        if (map.find(val) == map.end())
            return false;
        int index = map[val];
        map[vec.back()] = index;
        exchange(vec[index], vec[vec.size() - 1]);
        vec.pop_back();
        map.erase(val);
        return true;
    }

    /** Get a random element from the set. */
    int getRandom()
    {
        int n = vec.size();
        int index = generator() % n;
        return vec[index];
    }
};
3分钟搞懂欧式距离变换(EDT):从暴力算法到Felzenszwalb的演进史 本文系统梳理了欧式距离变换(EDT)从暴力算法到高效线性算法的演进历程。重点解析了光栅扫描算法和Felzenszwalb算法的核心思想与实现,并探讨了其在机器人路径规划中生成欧几里得符号距离场(ESDF)的关键应用,为开发者提供了清晰的算法选型与实战指南。 阅读详情

相关推荐

别再死磕RD算法了!用MATLAB手把手复现SAR后向投影(BP)成像(附完整代码与避坑点)

本文详细介绍了如何使用MATLAB实现合成孔径雷达(SAR)后向投影(BP)成像算法,突破传统RD算法在大斜视和复杂轨迹场景中的局限。通过完整的代码示例和避坑指南,帮助读者掌握BP算法的核心原理、内存优化策略和并行计算技巧,提升SAR成像精度与效率。

weixin_30908103的博客 298

380. Insert Delete GetRandom O(1)

设计一个数据结构,插入,删除,随机获取其中一个数值操作都是O(1)的时间复杂度。 思考:首先从基本的数据结构开始思考,数组、链表、hash表,map,set等等,发现单一的数据结构是无法支持那些操作都是O(1)的时间复杂度。进而再考虑叠加数据结构的方法。vector + unordered_map 是 不错的叠加方法,用数组存放具体数据,用hash表存放数据的索引。之后再查找时,可以通过索引,再...

李白-2017的博客 277

nRF开发环境搭建全攻略:VS Code + nRF Connect SDK + Zephyr实战

嵌入式开发中,环境配置往往是新手入门的第一道障碍,尤其面对基于Zephyr RTOS的Nordic nRF平台时,工具链的复杂度常让人望而却步。理解构建系统、SDK版本管理和调试工具之间的协作关系,是高效开发的前提。Zephyr作为开源实时操作系统,通过设备树和Kconfig实现硬件描述与功能配置,而nRF Connect SDK(NCS)则是Nordic基于Zephyr的增强发行版,两者结合为物联网开发提供了强大支持。基于VS Code搭建开发环境,配合west工具管理多仓库、CMake/Ninja执行构

weixin_29188997的博客 227

【Leetcode】380. Insert Delete GetRandom O(1)

题目地址: https://leetcode.com/problems/insert-delete-getrandom-o1/ 要求实现一个数据结构,可以在O(1)O(1)O(1)时间内: 1、添加一个数;添加成功则返回true,否则如果已经有了返回false; 2、删除一个数;删除成功则返回true,否则如果没有则返回false; 3、随机取出一个数,但每个数取到的概率要均等。 由于要实现删除一个数也要达到O(1)O(1)O(1),所以我们想到用一个HashMap记录每个数值出现的位置,删除的时候可以先把

数学、算法爱好者的博客 307

FreeRTOS-Plus-CLI在STM32F429上的高效移植与调试技巧

本文详细介绍了如何将FreeRTOS-Plus-CLI高效移植到STM32F429平台,并分享关键的调试技巧。内容涵盖使用HAL库进行底层驱动适配(特别是DMA+IDLE中断方案)、工程集成、自定义命令开发以及常见问题解决方案,旨在帮助开发者快速为嵌入式系统添加强大的命令行调试接口,提升开发与维护效率。

weixin_29224309的博客 336

Cadence IC 618实战:从与非门到环形振荡器的完整版图设计流程(含DRC/LVS避坑点)

本文详细介绍了使用Cadence IC 618进行从与非门到环形振荡器的完整版图设计流程,包括环境准备、基础设计规范、层次化设计、DRC/LVS验证及后仿真优化。特别提供了实战中的避坑技巧和优化建议,帮助工程师高效完成集成电路设计任务。

weixin_26886855的博客 405

[leetcode] 380. Insert Delete GetRandom O(1) 解题报告

题目链接: https://leetcode.com/problems/insert-delete-getrandom-o1/ Design a data structure that supports all following operations in average O(1) time. insert(val): Inserts an item val to the

小榕流光的专栏 3854

傻白入门芯片设计,芯片键合(Die Bonding)(四)

傻白入门芯片设计,芯片键合(Die Bonding)(四) 引线键合、倒装芯片键合、管脚贴合技术

qq_46675545的博客 3万+

【leetcode】Insert Delete GetRandom O(1)

Insert Delete GetRandom O(1)问题描述Design a data structure that supports all following operations in average O(1) time. insert(val): Inserts an item val to the set if not already present. remove(val): R

zgljl2012的专栏 1884

MIT 18.03 微分方程 ODE 学习笔记分享——目录

从B站上看到了MIT 微分方程的课程,觉得老爷子讲的真好! 其实微分方程对于工科来说相当重要,但是很多学习也仅把他放在高数里作为单独的一个章节来讲,这是远远不够的。所以对于同学们来说 ,一定要认真听讲,做好笔记! 以下是我的个人学习比较分享。有需要的同学可以做一个参考。 注:个人认为笔记的作用是用来回想起课堂所讲的内容(细节),所以我的笔记风格为以老师讲课思路为准,板书为辅。建议刚开始听这门课的同...

weixin_40664094的博客 2630

C#安装OpenCv及打开笔记本默认摄像头方法

C#安装OpenCv及打开笔记本默认摄像头方法

cg1135217680的博客 2572

【LeetCode】380. Insert Delete GetRandom O(1) 解题报告(Python)

【LeetCode】380. Insert Delete GetRandom O(1) 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/insert-delete-getrandom...

负雪明烛 3207

扫地机器人设计与实现——基于嵌入式系统的智能家居解决方案

本文介绍了基于嵌入式技术的扫地机器人设计与实现。通过利用STM32单片机、传感器、驱动系统等硬件组件,并结合路径规划与控制算法、远程控制等软件技术,设计出了一款具有智能避障、路径规划、自动充电等功能的扫地机器人。系统的开发不仅提高了清洁效率,也为进一步研究和优化扫地机器人提供了实践基础。

2201_76125393的博客 1639

[LeetCode] 380. Insert Delete GetRandom O(1)

380.Insert Delete GetRandom O(1) Medium 126395FavoriteShare Design a data structure that supports all following operations inaverageO(1)time. insert(val): Inserts an item v...

weixin_30301183的博客 115

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

LeetCode--380. Insert Delete GetRandom O(1) & 381. Insert Delete GetRandom O(1) - Duplicates allowed

问题链接:https://leetcode.com/problems/insert-delete-getrandom-o1/(Medium)和https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/(Hard) 设计一个支持插入、删除和随机取值(所有操作的时间复杂度为O(1))的数据结构。随机取值只能...

To_be_thinking的博客 178

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

leetcode(380). Insert Delete GetRandom O(1)

problem Design a data structure that supports all following operations in average O(1) time. insert(val): Inserts an item val to the set if not already present. remove(val): Removes an i

qishi的博客 362

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

leetcode 380. insert-delete-getrandom-o1 常数时间插入、删除和获取随机元素 python3

时间:2020-9-17 题目地址:https://leetcode-cn.com/problems/insert-delete-getrandom-o1/ 题目难度:Medium 题目描述: 设计一个支持在平均时间复杂度 O(1)下,执行以下操作的数据结构。 insert(val):当元素 val 不存在时,向集合中插入该项。 remove(val):元素 val 存在时,从集合中移除该项。 getRandom:随机返回现有集合中的一项。每个元素应该有相同的概率被返回。 示例 : // 初..

isabloomingtree的博客 264

leetcode380- Insert Delete GetRandom O(1)- medium

Design a data structure that supports all following operations inaverageO(1)time. insert(val): Inserts an item val to the set if not already present. remove(val): Removes an item val from th...

weixin_30588907的博客 93

LeetCode:381 Insert Delete GetRandom O(1)

381. Insert Delete GetRandom O(1) - Duplicates allowed Design a data structure that supports all following operations in average O(1) time. Note: Duplicate elements are allowed.

Wisimer 1144

[LeetCode] 380. Insert Delete GetRandom O(1) @ python

一.题目: 设计一个数据结构,有三个方法:插入、删除、随机选取一个数值。要求平均的时间复杂度是O(1). Example: // Init an empty set. RandomizedSet randomSet = new RandomizedSet(); // Inserts 1 to the set. Returns true as 1 was inserted successfully....

tmfighting的博客 195

leetcode380. Insert Delete GetRandom O(1)

题目要求 Design a data structure that supports all following operations in average O(1) time. insert(val): Inserts an item val to the set if not already present. remove(val)...

weixin_34007020的博客 149

LeetCode 中级 - Insert Delete GetRandom O(1)

Insert Delete GetRandom O(1) 设计一个支持在平均 时间复杂度 O(1) 下,执行以下操作的数据结构。 insert(val):当元素 val 不存在时,向集合中插入该项。 remove(val):元素 val 存在时,从集合中移除该项。 getRandom:随机返回现有集合中的一项。每个元素应该有相同的概率被返回。 示例 : // 初始化一个空的集合。 Ra...

whdAlive 's blog 758

Leetcode 380. Insert Delete GetRandom O(1) 常数增删改系统 解题报告

1 解题思想这道题是要设计一个常数时间内增加,删除,随机查询的数据结构,数值不会重复。重点在于如何做到常数内删除?思想其实也很简单,使用一个HashMap保存每个值的位置就可以了,然后全部值存到一个ArrayList里面,删除的时候讲删除的那个位置的值进行调换,将ArrayList里面最后一位的值提到要删除的那个位置上覆盖,然后直接删除ArrayList的最后一个对应的下一题,建议看完后再看这个:

MebiuW的专栏 2044

LeetCode 380. Insert Delete GetRandom O(1)

问题描述: Design a data structure that supports all following operations in average O(1) time. insert(val): Inserts an item val to the set if not already present.remove(val): Removes an item v

YXZreo的专栏 341
上一篇: LeetCode 42. Trapping Rain Water(Hard)
下一篇: LeetCode 328. Odd Even Linked List(Medium)
彼得.攀
博客等级 码龄11年 11粉丝 34原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值