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

在树莓派5(8G版)上运行Ollama + LLM 直接上结论,Ollama在树莓派上能安装,且本身运行起来毫无压力,但具体到大语言模型,Deepseek似乎不总是最佳选择。 阅读详情

查阅更多的题解,请点击

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];
    }
};
航天设备研制中的形态分类:电性件、正样件及其他关键形态详解 航天设备的研制是一个高度复杂且严谨的工程过程,涉及多个阶段的不同产品形态。这些形态各具特点,在研制流程中承担着不同的验证任务和工程目标。本文将系统介绍航天设备研制中的主要形态,包括**电性件(EM)**、**正样件(FM)**以及**结构热控件(STM)**、**鉴定件(QM)**和**初样件(PFM)**等,详细解析它们的定义、用途和工程意义,帮助读者全面理解航天产品从设计到飞行的全生命周期管理。 阅读详情

相关推荐

别再调参了!用Simulink手把手教你搞定FOC电机速度环PI控制器(附模型下载)

本文详细介绍了如何使用Simulink搭建FOC电机速度环PI控制器,通过模最优准则和系统化调试方法,避免传统手动调参的繁琐过程。文章包含从传递函数推导到参数自动整定的完整流程,并提供了实战调试技巧与异常处理指南,帮助工程师快速实现电机控制系统的稳定运行。

weixin_42519985的博客 415

380. Insert Delete GetRandom O(1)

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

李白-2017的博客 277

Unity Shader学习笔记/Urp/水墨风效果

Unity Shader学习

qq_63133691的博客 2117

【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

IC设计新手必看:如何正确使用去耦电容(decap)避免电源噪声?

本文深入探讨了IC设计中去耦电容(decap)的应用技巧,从核心原理到布局实现,帮助新手工程师有效抑制电源噪声。文章详细解析了MIM、MOM等电容类型的特性与选择策略,并提供了先进的布局技巧和验证方法,特别适用于28nm以下先进工艺的电路设计挑战。

weixin_30555125的博客 114

从Gotham到Foundry:一文读懂Palantir三大产品线(Gotham/Foundry/Apollo)的核心差异与适用场景

本文深度解析Palantir三大产品线Gotham、Foundry和Apollo的核心差异与适用场景。Gotham专为国防与情报设计,提供军事级安全分析;Foundry是企业数字化转型的通用平台,支持低代码开发;Apollo则是云原生基石,确保系统可靠运行。通过对比产品架构与典型应用,帮助技术决策者根据需求做出明智选择。

weixin_42524499的博客 840

[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

RK3588 平台部署实战:OpenCV + LibTorch + FFmpeg 环境搭建与深度学习推理全流程解析

现在,你已经掌握了在RK3588上搭建OpenCV+LibTorch+FFmpeg环境的完整流程,也完成了深度学习模型的部署测试。不妨从一个具体的应用场景入手(如检测自家宠物的品种),亲手打造属于你的第一个边缘智能应用——当你看到模型在RK3588上精准输出结果时,你会发现:嵌入式深度学习的门槛,其实并没有想象中那么高。这些依赖是编译OpenCV、FFmpeg的基础,安装过程中若提示权限不足,可在命令前加。若能输出预测的类别索引,则说明环境搭建成功,模型推理流程通畅。文件,实现模型加载、图像预处理与推理。

FJN110的博客 535

【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

TSP:车为什么能和云端交互?

TSP:车为什么能和云端交互?

天赐好车的博客 410

养龙虾之_因特尔UHD/ULtra/Arc核显跑大模型_安装ollama_跑qwen3.5:0.8b/9b_使用copaw1.0.1测试_并配置copaw技能效果炸裂---AI大模型应用探索0019

摘要:本文探讨了利用Intel UHD770核显运行大语言模型的可能性。通过使用Intel发布的ipex-llm项目工具包,成功在核显上运行了Qwen3.5系列模型。测试发现0.8B小模型运行流畅(3-5秒响应),但智能程度有限;而9B大模型虽然效果更好,但响应时间长达2分钟,且GPU/CPU占用率不高。实验证明Intel核显确实可以运行LLM,但实际效果和性能表现仍有提升空间,特别是对大模型的支持尚不理想。

添柴程序猿的专栏 235

【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

李宏毅2025《机器学习》第一讲-生成式AI:技术突破和未来发展

本文基于台湾大学李宏毅教授的“一堂课搞懂生成式人工智慧的技术突破与未来发展”课程内容,系统性地梳理了生成式AI的核心概念、技术原理、发展演进以及未来趋势。文章从AI的“行为”入手,通过生动的实例展示了其强大的生成与推理能力;进而深入剖析其底层运作机制,阐释了“万物皆为令牌(Token)”、自回归生成、Transformer架构等核心原理;接着,文章追溯了通用AI模型从“专才”到“通才”的演进历程;最后,探讨了如何通过微调(Fine-tuning)、模型编辑(Model Editing)等技术赋予AI新的能力

木鱼时刻的专栏 2295

[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

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

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

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

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

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

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、付费专栏及课程。

余额充值