leetcode 380. Insert Delete GetRandom O(1)(在O(1)时间添加,删除,取随机)

云端办公文件存储与访问全攻略:选型、预算、实操一本通 随着远程办公、多设备协作成为常态,“文件云端存储、随时调用” 已成为提升办公效率的核心需求。本文从用户实际场景出发,系统拆解云端存储的选型逻辑、全场景费用预算,重点解答 “文件能否直接在线打开” 的核心疑问,并提供实操技巧与安全保障方案,覆盖个人、小团队(含兼职)、企业全维度需求,帮助不同规模用户快速搭建高效、低成本的云端办公体系。 阅读详情

Implement the RandomizedSet class:

RandomizedSet() Initializes the RandomizedSet object.
bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise.
bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise.
int getRandom() Returns a random element from the current set of elements (it’s guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned.
You must implement the functions of the class such that each function works in average O(1) time complexity.

Example 1:

Input
[“RandomizedSet”, “insert”, “remove”, “insert”, “getRandom”, “remove”, “insert”, “getRandom”]
[[], [1], [2], [2], [], [1], [2], []]
Output
[null, true, false, true, 2, true, false, 2]

Explanation
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomizedSet.remove(2); // Returns false as 2 does not exist in the set.
randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2].
randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.
randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2].
randomizedSet.insert(2); // 2 was already in the set, so return false.
randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.

实现一个RandomizedSet类,它具有以下功能:
能在O(1)时间添加和删除元素,
并能在O(1)时间内,在现有的元素中随机(均匀分布)取一个。

添加元素时如果元素已经存在,返回false, 否则添加之后返回true.
删除元素也是一样,已经不存在的返回false, 否则删除完返回true.

思路:

在O(1)时间内添加和删除元素到是简单,一个hashset就搞定了。
问题在于如何在O(1)时间内随机返回现有数字中的一个,而且是均匀分布。

这里用Java, 不像cpp那样next函数可以直接指定偏移量从set中取值。

科普一下,random类中的nextInt(n)是从[0, n)中按均匀分布取值的。
把它当作下标的话,就只能从数组或list中取值了。
用数组不太现实,因为val的范围太广了,那么只能用list。

但是list有个问题,是它的删除不是O(1)的,因为要查找元素在哪,删除后还要移位。
那么问题就变成如何在O(1)时间从list中删除元素。
如果不需要查找,直接删除末尾的元素,类似pop,就是O(1),移位也省了.
那么就要把要删除的元素换到末尾去,
怎么在O(1)时间找到要删除的元素在哪呢,只需要在insert时记下它的下标。
所以需要一个hashmap.
换元素时,不要忘了更新hashmap中元素对应的下标。

class RandomizedSet {
    HashMap<Integer,Integer> map;
    List<Integer> arr;
    Random rd;

    public RandomizedSet() {
        map = new HashMap<>();
        arr = new ArrayList<>();
        rd = new Random();
    }
    
    public boolean insert(int val) {
        if(map.containsKey(val)) return false;
        map.put(val,arr.size());
        arr.add(val);
        return true;
    }
    
    public boolean remove(int val) {
        if(!map.containsKey(val)) return false;
        int valIdx = map.get(val);
        int lastItem = arr.get(arr.size()-1);
        //把val放到最后面去,最后面的元素值放到valIdx处,然后直接移掉list的最后一个元素
        arr.set(valIdx, lastItem);
        map.put(lastItem, valIdx); //map中要更新lastItem的index
        //arr.set(arr.size()-1, val); //反正都要remove了,还设置它干嘛
        arr.remove(arr.size()-1);
        
        map.remove(val);
        
        return true;
    }
    
    public int getRandom() {
        return arr.get(rd.nextInt(arr.size()));
    }
}

2025年广东省职业院校技能大赛高职组“区块链技术应用”正式赛题解析答案(标准答案参阅) 某公司规划开发一个区块链供应链金融平台,包括核心企业、供应商、银行等角色,通过智能合约代码逐步构建区块链供应链金融平台的基本功能,实现银行向核心企业提供授信并发行数字凭证,企业与企业之间转让数字凭证。此外需要完成区块链供应链金融平台的前后端,实现基本的业务逻辑 阅读详情

相关推荐

莫兰指数stata命令_一文读懂16个sp系列stata空间计量命令及应用

spcompress:Compress Stata-format shapefile压缩数据成stata格式的shapefile2、Looking at data/观测数据2、Looking at data/观测数据grmap:Graph choropleth maps绘制等值区域图spdistance:Calculator for distance between places计算区域之间距离3...

weixin_39719989的博客 823

LeetCode 380. Insert Delete GetRandom O(1) 题解

本题是数据结构设计中的经典问题,考察如何组合不同的数据结构来实现高效的操作。哈希表 + 数组的组合删除操作的优化:与最后一个元素交换随机访问:使用 random.choice通过本题可以深入理解如何设计高效的数据结构,以及如何在时间和空间之间做出权衡。

cannonjinx的博客 4130

MSTAR数据集下载地址及处理方法

首先感谢博主冯子材提供下载的百度网盘地址。 在这里为了防止侵权,特此鸣谢,并给出其博客地址。 地址中有MSTAR百度网盘下载地址和需要使用的数据介绍,其中百度网盘中有数据转换工具 https://blog.csdn.net/taifengzikai/article/details/80600355 工具使用 因为下载得到的数据是二进制文件,需要使用官方提供的工具进行转换,可将其转换为jpeg。 有...

KamenRider 1万+

380. Insert Delete GetRandom O(1)

380. Insert Delete GetRandom O(1)标签(空格分隔): leetcode array medium题目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

分享人工智能学习心得与实践经验,探讨应用场景,见证变革与进步 763

Yolov5实现道路裂缝检测

Yolov5实现道路裂缝检测 参考代码链接 Github代码链接 基于Pytorch的Yolov5道路裂缝检测程序运行说明。大家可以结合我的说明和原文说明使用,有问题欢迎询问。 文章目录Yolov5实现道路裂缝检测环境要求测试训练自己的数据集1.创建dataset.yaml文件2.创建标签文件3.组织文件路径4.选择模型5.开始训练 环境要求 Python 3.8或之后的版本 还要安装requirements.txt文件中所有依赖包,包括1.7及以上版本的torch $ pip install -r req

qq_26751379的博客 2万+

从拆解图看懂空心杯电机:有刷 vs 无刷内部结构全解析(附DIY注意事项)

本文深入解析有刷与无刷空心杯电机的内部结构差异,通过高清拆解图展示关键部件工艺特点,并分享实用的维护技巧和检测方法。重点对比两种电机在效率、寿命和适用场景上的优劣,为DIY爱好者提供详细的注意事项和操作指南。

xgboost6farmer的博客 531

[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

小榕流光的专栏 3855

WPF基础系列六:MVVM框架

MVVM框架 文章目录MVVM框架前言一、MVVM框架简介1. 什么是MVVM?2. MVVM的优势3.MVVM的应用场景二、MVVM使用及示例 前言 在WPF开发中,经典的编程模式是MVVM,是为WPF量身定做的模式,该模式充分利用了WPF的数据绑定机制,最大限度地降低了Xmal文件和CS文件的耦合度,也就是UI显示和逻辑代码的耦合度,如需要更换界面时,逻辑代码修改很少,甚至不用修改。 与WinForm开发相比,我们一般在后置代码中会使用控件的名字来操作控件的属性来更新UI,而在WPF中通常是通过

iceberg7012的博客 2万+

【Leetcode】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

业精于勤,荒于嬉 4604

100天精通Python(爬虫篇)——第114天:爬虫基础模块之requests基础入门

一、request模块大总结 1. 下载安装 2. 常用属性或方法 3. response.text和response.content的区别: 4. 发送带headers参数请求 5. 发送带参数请求 6. 在headers参数中携带cookie 7. 超时参数timeout的使用 8. proxies代理参数的使用 9. 发送post请求...............

努力让自己发光,对的人才能迎着光而来 11万+

1000路监控IP地址规划的方法与思路!看完就会!超简单!

四个区域ip地址比较明显了,如果那个摄像机有问题,可以直接通过批量ping ip地址可以很快定位到那个摄像机出了问题,同时也可以有效防止ip冲突,ip是网络故障中出现频率比较高的问题,也可以减少广播风暴。,如果让系统自动分配ip地址的话,容易产生ip冲突,所以1000路监控的ip地址不能只有一个大网段,我们需要对其划分vlan,方便管理和减少网络故障。”,如果你在开始了dhcp自由分配ip地址的话,容易出现ip冲突等问题,所以设置时需要注意。255.255.252.0,可以容纳,4*254个ip地址。

qq_43416206的博客 509

​力扣解法汇总380- O(1) 时间插入、删除和获取随机元素

目录链接: 力扣编程题-解法汇总_分享+记录-CSDN博客 GitHub同步刷题项目: https://github.com/September26/java-algorithms 原题链接:力扣 描述: 实现RandomizedSet 类: RandomizedSet() 初始化 RandomizedSet 对象 bool insert(int val) 当元素 val 不存在时,向集合中插入该项,并返回 true ;否则,返回 false 。 bool remove(int v.

分享+记录 1931

告别繁琐!VS Code 下OpenClaw零配置上手秘籍

本文介绍了在VSCode环境下零配置上手OpenClaw开发工具的最佳实践。首先详细说明了VSCode和OpenClaw插件的安装步骤,包括获取安装包、配置环境变量等准备工作。然后重点讲解了核心配置流程:设置OpenClaw路径、调整工作区参数、添加自定义代码片段等优化开发体验的方法。通过创建测试项目验证配置有效性,并针对常见的路径错误、运行报错等问题提供了排查方案。本文旨在帮助开发者快速搭建高效的OpenClaw开发环境,充分发挥VSCode与OpenClaw的组合优势,提升开发效率。无论是新手还是资深开

远程部署调试 运行安装 项目调试 二次开发 项目技术新 持续迭代 部分源码免费分享 536

【LeetCode 面试经典150题】380. Insert Delete GetRandom O(1) O(1) 时间插入、删除和获取随机元素

类,该类支持在平均 O(1) 时间复杂度内执行插入、删除和获取随机元素的操作。算法的关键点在于使用一个哈希表和一个动态数组来有效地管理元素。

qq_43513394的博客 847

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

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

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

LeetCode Top Interview Questions 380. Insert Delete GetRandom O(1) (Java版; Meidum)

welcome to my blog LeetCode Top Interview Questions 380. Insert Delete GetRandom O(1) (Java版; Meidum) 题目描述 Design a data structure that supports all following operations in average O(1) time. insert...

littlehaes的博客 318

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

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

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

查阅更多的题解,请点击 Problem 380. Insert Delete GetRandom O(1)(Medium) 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 a...

彼得.攀的blog 289

leetcode-380-常数时间插入、删除和获取随机元素(Insert Delete GetRandom O(1))-java

题目及测试 package pid381; /* Insert Delete GetRandom O(1) 设计一个支持在平均 时间复杂度 O(1) 下,执行以下操作的数据结构。 insert(val):当元素 val 不存在时,向集合中插入该项。 remove(val):元素 val 存在时,从集合中移除该项。 getRandom:随机返回现有集合中的一项。每个元...

今天吃了吗的博客 1086

Leetcode六月挑战赛(6.12)LeetCode380 Insert Delete GetRandom O(1)解题方案

Leetcode六月挑战赛(6.12) 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):

初七的博客 128

LeetCode - 380. Insert Delete GetRandom O(1)-思路详解

设计一个数据结构,该数据可以在O(1)时间内完成以下操作: 1,insert(val):插入一个元素到集合中,如果元素之前不存在。 2,remove(val):如果val在集合中存在,则删除 3,getRandom:返回当前集合中随机的一个数。每个元素返回的概率相同。

SJWL2012的专栏 990

【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的专栏 1885

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

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.re

zhizhi_zhizhi_zhizhi的博客 365

LeetCode 380. Insert Delete GetRandom O(1)

LeetCode 380. Insert Delete GetRandom O(1) (Medium) 优先级:4;主要知识点:hashmap

温迪今天刷题了吗 844

LeetCode-380. Insert Delete GetRandom O(1) [C++][Java]

You must implement the functions of the class such that each function works inaverageO(1)time complexity.

贫道绝缘子的博客 502

LeetCode 380: 常数时间插入、删除和获取随机元素 Insert Delete GetRandom O(1)

题目: 设计一个支持在平均 时间复杂度 O(1) 下,执行以下操作的数据结构。insert(val):当元素 val 不存在时,向集合中插入该项。remove(val):元素 val 存...

爱写Bug 322

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

380. Insert Delete GetRandom O(1)https://leetcode.com/problems/insert-delete-getrandom-o1/?tab=Description Design a data structure that supports all following operations in average O(1) time. in

xxxxzr的博客 367

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

[leetcode]380. Insert Delete GetRandom O(1) Analysis 出太阳啦~—— [每天刷题并不难0.0] Design a data structure that supports all following operations in average O(1) time. insert(val): Inserts an item val to ...

weixin_32135877的博客 263

LeetCode - 380. Insert Delete GetRandom O(1) (常数时间插入、删除和获取随机元素)

LeetCode - 380. Insert Delete GetRandom O(1) (常数时间插入、删除和获取随机元素) HashMap + List 实现 两个HashMap实现 题目链接 题目 HashMap + List 实现 解析: 准备一个HashMap和一个List容器,HashMap存放val到index的映射,List容器中存放val集合; insert(): 将...

zxzxin的博客~ 465
上一篇: leetcode 1207. Unique Number of Occurrences(出现次数的唯一性)
下一篇: leetcode 328. Odd Even Linked List(奇偶链表)
蓝羽飞鸟
博客等级 码龄8年 1万+粉丝 727原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值
⌂ 换网址