380. 常数时间插入、删除和获取随机元素/C++

【C++】每日一题 380 O(1)时间插入,删除和获取随机元素 第一行代码是从 nums 向量中删除这个索引位置的元素,但是删除后,后面的元素会向前移动填补被删除的位置,这就会导致原来在 indices[val] 位置的元素变成了新的 val,而且 val 在 nums 中的位置已经改变了,所以删除 val 对应的索引值并不正确。同时,使用一个 vector 来存储集合中的值,并且通过将被删除元素与最后一个元素交换,然后再删除最后一个元素的方式来实现 O(1) 时间复杂度的删除操作。正确的做法是通过交换最后一个元素和要删除的元素来实现删除,然后更新映射。 阅读详情

在这里插入图片描述

class RandomizedSet {
    unordered_map<int,int> hash;
    vector<int> vec;
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(hash.count(val))
            return false;
        vec.push_back(val);
        hash[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(!hash.count(val))
            return false;
        hash[vec.back()] = hash[val];
        swap(vec.back(),vec[hash[val]]);
        vec.pop_back();
        hash.erase(val);
        return true;
    }
    
    /** Get a random element from the set. */
    int getRandom() {
        if(vec.empty()) return 0;
        return vec[rand()%vec.size()];
    }
};

/**
 * Your RandomizedSet object will be instantiated and called as such:
 * RandomizedSet* obj = new RandomizedSet();
 * bool param_1 = obj->insert(val);
 * bool param_2 = obj->remove(val);
 * int param_3 = obj->getRandom();
 */
Linux服务器遇到攻击封禁IP、解封IP Linux服务器遇到攻击封禁IP与解封IP 阅读详情

相关推荐

bcftools学习笔记(一)

欢迎关注"生信修炼手册"!本篇主要介绍index, view, query, sort, reheader这五个命令。1. indexindex命令用于对VCF文件建立索...

庐州月光的博客 6020

LeetCode面试150——380. O(1) 时间插入、删除和获取随机元素

LeetCode面试150——380. O(1) 时间插入、删除和获取随机元素题目讲解和代码实现

Junmo12345的博客 1292

FPGA新手必看:用USB转TTL实现串口通信的完整流程(附CH340G电路详解)

本文为FPGA新手提供了通过USB转TTL模块实现串口通信的完整实战指南。详细解析了CH340G电路设计要点、硬件连接方法,并分享了经过验证的Verilog代码框架,帮助读者快速掌握FPGA与PC通信的核心技术,解决电平匹配与波特率设置等常见问题。

cake8的博客 1060

LeetCode---380周赛

LeetCode---380周赛---数位dp/找规律+KMP

V_zjs的博客 1240

二叉树随机漫步

元旦快乐! 学习到中本聪bitcoin的文章的calculation部分的时候,出现了binomial random walk,不是很明白什么是random walk。发现这个文章写的很好:https://blog.csdn.net/fireguard/article/details/16111603 随机漫步,也叫随机游走,最早是物理学中做"布朗运动"的微观粒子的运动形态来形成的一个模型,布朗运...

gjq5464的博客 1742

[软考]系统架构设计师 备考经验分享(一) - 备考计划篇

前言 上周末刚刚结束了软考架构师的考试,自我感觉考的还可以,大概率是过了。 两次参加软考,一次中级嵌入式,一次高级架构师,都是备考不到两个月时间,尤其是架构师这次考试内容和本职工作有不小的差别,并且需要同时备考三个科目,在高强度地备考中感觉是摸索出到了一点软考的技巧与经验。 打算趁还记得,赶紧写几篇文章做下梳理总结,算是给将来自己考系分、高项或者其他考试做个记录,也希望能够帮到正在备考的大家。 先把第一步,个人的备考计划分享给大家。 自身情况分析 首先,请大家一定先明确三个问题,这三个问题会直接影响到你的

_ 6414

【Leetcode】380. 常数时间插入、删除和获取随机元素

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

zzy0006的博客 234

从底层结构开始学习FPGA(7)----进位链CARRY4

进位链CARRY4在FPGA实现加减法运算时扮演了什么角色?

孤独的单刀 1万+

Leetcode 380

【代码】Leetcode 380。

SUNSKU的博客 363

【云原生技术】SonarQube 生态中PMD插件和P3C插件详细介绍

4. 在项目中如何选择 / 组合 1. 小团队、对《阿里规约》认同度高 → 直接启用 **P3C**,配合 SonarJava 基本够用。 2. 追求全面 Bug/安全检测 + 额外编码规范 → **SonarJava + PMD**(必要时加 P3C 少量规则)。 3. 大型多团队,希望“一本规约”统一风格 → **P3C 为主**,再补充 SonarJava/PMD 的 Bug 与安全规则。 4. 通过 Quality Gate 控制:将 **Blocker/Critical** Bug

weixin_46453070的博客 1373

7、基于机器学习的生产效率估计方法解析

本文探讨了基于机器学习的生产效率估计方法,重点介绍了效率分析树(EAT)和凸效率分析树(CEAT)算法的原理及其与传统自由处置壳(FDH)和数据包络分析(DEA)方法的对比。通过剪枝优化、生产可能性集构建及方向距离函数(DDF)估计,EAT和CEAT在避免过拟合、提升估计稳定性与处理凸性假设方面展现出优势。结合PISA教育数据的实证研究,采用箱线图、核密度图和非参数检验方法验证了不同模型效率得分分布的显著差异。研究表明,EAT与CEAT为生产效率评估提供了更准确、灵活的工具,适用于教育、企业生产和医疗等多个

milk5的博客 98

Leetcode刷题380. 常数时间插入、删除和获取随机元素

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

Bonbon_wen的博客 379

10天冲刺国自然基金!用这套实战AI提示词指令教程,助你中标率翻倍!亲测DeepSeek和ChatGPT不好用

虽然以上国自然提示词指令经过反复实测,但并不是万能无脑帮你搞定所有,大模型AI的特性是你专业领域能力越强,它的智商表现就会更加强大,通过以上提示词教程的使用,大大提升中标概率是肯定的。还有就是大模型的使用上,不是市面上大家都说好的就一定适用,目前来看,Gemini和Claude的两个模型是非常适合国自然本子的修改的。在使用大模型进行国自然本子撰写修改时,首先是角色的设定,然后是目标和背景的描述,好用的提示词指令都是要经过无数次的实测,比对输出结果后又反复调整,达到最佳的效果状态的提示词指令。

智能AI让学术科研更容易 1268

Leetcode 380. 常数时间插入、删除和获取随机元素 C++

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

weixin_43750513的博客 350

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

LeetCode 常数时间插入、删除和获取随机元素

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

hestyle的博客 1108

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

面试经典150题[012]:O(1) 时间插入、删除和获取随机元素(LeetCode 380)

面试经典150题[012]:O(1) 时间插入、删除和获取随机元素(LeetCode 380)

YoungHong1992 828

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

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

[LeetCode] 380. O(1) 时间插入、删除、获取随机元素

实现valtruefalsevaltruefalse你必须实现类的所有函数,并满足每个函数的时间复杂度为O(1)。// 向集合中插入 1。返回 true 表示 1 被成功地插入。// 返回 false ,表示集合中不存在 2。// 向集合中插入 2。返回 true。集合现在包含[1,2]。// getRandom 应随机返回 1 或 2。// 从集合中移除 1 ,返回 true。集合现在包含[2]。// 2 已在集合中,所以返回 false。

gulugulu1103的博客 1303

[LeetCode] 380.常数时间插入、删除和获取随机元素(Medium)C语言题解

题目 设计一个支持在平均 时间复杂度 O(1) 下,执行以下操作的数据结构。 insert(val):当元素 val 不存在时,向集合中插入该项。 remove(val):元素 val 存在时,从集合中移除该项。 getRandom:随机返回现有集合中的一项。每个元素应该有相同的概率被返回。 示例 ①示例1 说明 ①数据范围(自测) -2147483648 ~ 2147483647 ...

wjy的博客 587

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

vector+哈希表

cwtnice的博客 1155

380.常数时间插入、删除和获取随机元素

class RandomizedSet { public: vector<int> arr; unordered_map<int,int> mp; /** Initialize your data structure here. */ RandomizedSet() { } /** Inserts a valu...

qq_43604517的博客 164

(数组/字符串) 380. O(1) 时间插入、删除和获取随机元素 ——【Leetcode每日一题】

380. O(1) 时间插入、删除和获取随机元素 实现RandomizedSet 类: RandomizedSet() 初始化 RandomizedSet 对象 bool insert(int val) 当元素 val 不存在时,向集合中插入该项,并返回 true ;否则,返回 false 。 bool remove(int val) 当元素 val 存在时,从集合中移除该项,并返回 true ;否则,返回 false 。 int getRandom() 随机返回现有集合中的一项(测试用例保证调用此方法时

weixin_43412762的博客 1049

380. 常数时间插入、删除和获取随机元素

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

路漫漫其修远兮 236

LeetCode 面试经典 150_数组/字符串_O(1)时间插入、删除和获取随机元素(12_380_C++_中等)(哈希表)

LeetCode 面试经典 150_数组/字符串_O(1)时间插入、删除和获取随机元素(12_380_C++_中等) 实现RandomizedSet 类: RandomizedSet() 初始化 RandomizedSet 对象 bool insert(int val) 当元素 val 不存在时,向集合中插入该项,并返回 true ;否则,返回 false 。 bool remove(int val) 当元素 val 存在时,从集合中移除该项,并返回 true ;否则,返回 false。

huayimenghan的博客 1011

【Leetcode】380. 常数时间插入、删除和获取随机元素(中等)

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

qq_40173961的博客 233

【面试经典150 | 数组】O(1) 时间插入、删除和获取随机元素

设计一个 可以实现O(1) 时间插入、删除和获取随机元素的类。

weixin_54383080的博客 427

力扣第380题插入删除和获取随机元素

力扣第380题插入删除和获取随机元素 实现RandomizedSet 类: RandomizedSet() 初始化 RandomizedSet 对象 bool insert(int val) 当元素 val 不存在时,向集合中插入该项,并返回 true ;否则,返回 false 。 bool remove(int val) 当元素 val 存在时,从集合中移除该项,并返回 true ;否则,返回 false 。 int getRandom() 随机返回现有集合中的一项(测试用例保证调用此方法时集合中至少存在

JB666M的博客 318
上一篇: 162. 寻找峰值/C++
下一篇: 50. Pow(x, n)/C++
Lambda_eta
博客等级 码龄11年 49粉丝 284原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值