LeetCode 中级 - Insert Delete GetRandom O(1)

形位公差标注的常见误区与优化策略 本文深入解析机械设计中形位公差标注的常见误区与优化策略,特别针对NX2406用户提供实用技巧。从标注冗余、基准选择到公差值设定等五大误区入手,结合工程图实例展示如何提升标注精度与效率,帮助工程师避免常见错误,优化设计流程,确保零件功能实现与制造可行性。 阅读详情

Insert Delete GetRandom O(1)

设计一个支持在平均 时间复杂度 O(1) 下,执行以下操作的数据结构。

  1. insert(val):当元素 val 不存在时,向集合中插入该项。
  2. remove(val):元素 val 存在时,从集合中移除该项。
  3. getRandom:随机返回现有集合中的一项。每个元素应该有相同的概率被返回。

示例 :

// 初始化一个空的集合。
RandomizedSet randomSet = new RandomizedSet();

// 向集合中插入 1 。返回 true 表示 1 被成功地插入。
randomSet.insert(1);

// 返回 false ,表示集合中不存在 2 。
randomSet.remove(2);

// 向集合中插入 2 。返回 true 。集合现在包含 [1,2] 。
randomSet.insert(2);

// getRandom 应随机返回 1 或 2 。
randomSet.getRandom();

// 从集合中移除 1 ,返回 true 。集合现在包含 [2] 。
randomSet.remove(1);

// 2 已在集合中,所以返回 false 。
randomSet.insert(2);

// 由于 2 是集合中唯一的数字,getRandom 总是返回 2 。
randomSet.getRandom();

分析

如果不限制复杂度,那么只要有一个List就可以了,然而list.contains()方法实在是效率不高,由于O(1)的限制,我们就需要一个hashmap来存放集合中的数值,判断是否存在也是靠hashmap。

解法就是 利用hashmap存放数值及其在list中的存放下标,list则单纯存放数值。

要注意当删除元素时,我们要将list末尾元素调整到删除的元素位置,否则list自动排列,又无法满足O(1)。

代码

    class RandomizedSet {

        List<Integer> list;
        int num;
        Map<Integer,Integer> map;
        /** Initialize your data structure here. */
        public RandomizedSet() {
            list = new ArrayList<>();
            num = 0;
            map = new HashMap<>();
        }

        /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
        public boolean insert(int val) {
            if(map.containsKey(val)){
                return false;
            }else{
                list.add(num,val);
                map.put(val,num++);
                return true;
            }
        }

        /** Removes a value from the set. Returns true if the set contained the specified element. */
        public boolean remove(int val) {
            if(!map.containsKey(val)){
                return false;
            }else if(num == 0){
                map.remove(val);
                return true;
            }else{
                int removedIndex = map.get(val);
                int lastElement = list.get(num-1);
                map.put(lastElement,removedIndex);
                list.set(removedIndex,lastElement);
                num--;
                map.remove(val);
                return true;
            }
        }

        /** Get a random element from the set. */
        public int getRandom() {
            Random random = new Random();
            return list.get(random.nextInt(num));
        }
    }

    /**
     * Your RandomizedSet object will be instantiated and called as such:
     * RandomizedSet obj = new RandomizedSet();
     * boolean param_1 = obj.insert(val);
     * boolean param_2 = obj.remove(val);
     * int param_3 = obj.getRandom();
     */
铝合金外壳表面处理工艺全解析:从阳极氧化到瓷泳喷涂的7种方法对比 本文全面解析了铝合金外壳的7种主流表面处理工艺,包括阳极氧化、粉末喷涂、瓷泳喷涂等。通过对比其原理、性能、成本与应用场景,为产品设计师和工程师提供了从防护性、装饰性到功能性的立体选型框架,帮助您根据具体需求选择最佳工艺方案。 阅读详情

相关推荐

Anaconda安装及配置+pytorch深度学习环境(2024复旦计算机工作站0705)

Pytorch是torch的python版本,是由Facebook开源的神经网络框架,专门针对 GPU 加速的深度神经网络(DNN)编程。Torch 是一个经典的对多维矩阵数据进行操作的张量(tensor )库,在机器学习和其他数学密集型应用有广泛应用。与Tensorflow的静态计算图不同,Pytorch的计算图是动态的,可以根据计算需要实时改变计算图。但由于Torch语言采用 Lua,导致在国内一直很小众,并逐渐被支持 Python 的 Tensorflow 抢走用户。

ZhiYilang的博客 2348

Insert Delete GetRandom O(1)

设计一个数据结构实现在平均O(1)的复杂度下执行以下所有的操作。 insert(val): 如果这个元素不在set中,则插入。 remove(val): 如果这个元素在set中,则从set中移除。 getRandom: 随机从set中返回一个元素。每一个元素返回的可能性必须相同。 样例 // 初始化空集set RandomizedSet randomSet =...

weixin_41791402的博客 203

CAPL实战:从零构建HEX文件解析器,赋能UDS刷写

本文详细介绍了如何使用CAPL从零构建HEX文件解析器,以支持UDS刷写操作。通过解析HEX文件格式、设计状态机、优化数据结构与算法,实现高效准确的固件数据处理,并提供了与UDS刷写流程对接的工程化实践建议。

weixin_28726391的博客 444

380. Insert Delete GetRandom O(1)

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

李白-2017的博客 277

R语言分类变量的统计描述

三篇介绍了连续变量的统计描述的R语言相关函数,计算数值的相关统计指标。本文介绍分类变量的统计描述及如何在R语言中实现。 不同于连续变量,分类变量的统计描述主要是汇总分类变量各类别例数及百分比。 1、table()函数 ...

zsc943290710的博客 1万+

【ESP32】ESP32连接JY61P并通过WIFI发送给电脑

ESP32S连接JY61P并通过WIFI把姿态数据发送给电脑1.采用Arduino IDE编译器;需要安装ESP32的开发板管理器;2.电脑接受数据是基于python的;

Doudou_Nai的博客 1132

【leetcode】Insert Delete GetRandom O(1)

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

kangbin825的专栏 6596

深入解析Transformer三大注意力机制:自注意力、交叉注意力与因果自注意力

注意力机制是深度学习中的核心概念,它模拟了人类在处理信息时选择性聚焦的能力。其基本原理是通过计算查询与键的相似度,动态地为值分配权重,从而提取关键信息。这一机制解决了传统序列模型(如RNN)难以并行化和捕获长距离依赖的痛点,技术价值在于显著提升了模型的计算效率和表征能力。在自然语言处理、计算机视觉等应用场景中,注意力机制已成为构建强大模型的基石。本文聚焦于Transformer架构中的三种核心注意力变体:自注意力用于建立序列内部的全局关联,交叉注意力连接编码器与解码器的信息,而因果自注意力则确保自回归生成的

weixin_29094775的博客 413

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

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

SJWL2012的专栏 989

杰理SDK入门教程(五):按键使用配置

摘要 杰理SDK提供IO按键和AD按键两种方案。IO按键通过GPIO电平检测实现,配置时需要设置板级宏定义和硬件连接,默认使用PB1引脚。AD按键基于ADC电压采样,通过电阻分压区分按键,需配置功能使能、硬件通道和键值适配。按键功能通过修改SDK中的key_table文件实现。两种方案适用于不同硬件场景,开发者可根据需求选择。

qq_42014563的博客 776

33、密码学中的选择密文攻击与Cramer - Shoup加密方案

本文详细介绍了密码学中选择密文攻击的背景及其对Cramer-Shoup公钥加密方案的影响。该方案在决策Diffie-Hellman假设和抗碰撞哈希函数的基础上,能够有效抵御自适应选择密文攻击,并且其安全性无需依赖随机预言机模型。文章还分析了Cramer-Shoup方案的设计原理、加密与解密过程,以及其在标准假设下的安全性证明方法。此外,通过一系列相关练习,帮助读者进一步理解密码学概念如密文不可区分性、ElGamal加密、Goldwasser-Micali方案等。最后,文章展望了密码学的未来发展趋势,包括量子

vscode6remote的博客 99

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

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

cannonjinx的博客 4130

【汽车 OTA 】差分升级

汽车 OTA 差分升级,本质是在整包 OTA 的基础上,通过“只传变化”的方式,大幅减少下载数据量、时间和成本,是当前车端软件升级的主流方向之一。

天赐好车的博客 482

【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

业精于勤,荒于嬉 4602

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

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

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

[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

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

【Leetcode】Insert Delete GetRandom O(1) - Duplicates allowed

题目链接:https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/ 题目: Design a data structure that supports all following operations in average O(1) time. Note: Duplicate elemen

业精于勤,荒于嬉 2910

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

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):

初七的博客 127

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的博客 317

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 val from the

夜色之浓,莫过于黎明前的黑暗。 303

Leetcode 之 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 val from the set

思念 1387

【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的博客 366

LeetCode //C++ - 381. Insert Delete GetRandom O(1) - Duplicates allowed

【代码】LeetCode //C++ - 381. Insert Delete GetRandom O(1) - Duplicates allowed。

Made in Code 828

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)

[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的博客 262
上一篇: LeetCode 中级 - Longest Increasing Subsequence
下一篇: LeetCode 中级 - 快乐数
whd_Alive
博客等级 码龄9年 107粉丝 195原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值