1. 两数之和

哈希应用之两数之和 阅读详情

题目

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

方法一 – 暴力求解

两层for循环

方法二 – 两遍哈希表

步骤:
  1. 遍历数组,将数据中的元素放入到哈希表中
  2. 遍历数组,从哈希表中寻找是否有相加和为target的数据
注意点:

第二次遍历数组的时候,第一次遇到相加和为target的数据的时候,就应该退出循环,如果不退出,将会有两个结果,比如第一次匹配到了1,2,那么还会匹配一次2,1

代码:
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> arr;
        unordered_map<int,int> nums_map;
        for (int i = 0; i < nums.size(); ++i) {
            nums_map.insert(pair<int,int>(nums[i],i));
        }
        for (int i = 0; i < nums.size(); ++i) {
            if (nums_map.find(target - nums[i]) != nums_map.end() && nums_map.find(target - nums[i])->second != i) {
                arr.push_back(i);
                arr.push_back(nums_map.find(target - nums[i])->second);
                break;
            }
        }
        return arr;
    }
};

方法三 – 一遍哈希表

思路

方法二中需要先把数据全部放入到哈希表中,然后查找
方法三是让数据的时候一边放一边查找,即使从先查的nums中找不到后面的数据,但是后面的数据在查找的时候,前面的数据已经放在了哈希表中了

代码
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> arr;

        unordered_map<int,int> nums_map;
        for (int i = 0; i < nums.size(); ++i) {
            if (nums_map.find(target - nums[i]) != nums_map.end()) {
                arr.push_back(i);
                arr.push_back(nums_map.find(target - nums[i])->second);
            } else {
                nums_map.insert(pair<int,int>(nums[i],i));
            }
        }
        return arr;
    }
};
1 两数之和 文章摘要 本文介绍了LeetCode经典题目"两数之和"的两种解法:暴力枚举法和哈希表法。暴力枚举法通过双重循环遍历所有组合寻找和为target的两个数,时间复杂度O(n²)。哈希表法利用字典存储数值和索引,通过一次遍历实现快速查找,时间复杂度O(n)。两种方法都能正确解决问题,但哈希表法效率更高。文中提供了Python实现代码,并包含示例说明。 阅读详情

相关推荐

版电力系统故障录波_故障录波识图与典型故障波形分析

1、设置故障录波的目的故障录波装置是对电力系统运行状况进行监控的一种自动化设备。系统正常运行时,录波装置不启动录波,当系统发生故障时,通过启动录波装置迅速启动录波器录波,直接记录反应故障装置安装处系统故障的电气量。2、故障录波的作用(1)正确评价继电保护和自动装置的工作。(2)正确分析事故的原因并研究防止对侧。(3)发现继电保护和自动装置缺陷。(4)发现一次设备缺陷,及时消除隐患。(5)帮助寻找故...

weixin_42495661的博客 1万+

Leetcode:两数之和

问题描述: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。 例如 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] 一、暴力循...

baidu_32109835的博客 137

支付漏洞防护绕过的一种方式

放完包后就到了提交订单的地方,可以发现,金额确实小了很多,合理的搭配的话还可以更低,再次前进可以发现,金额确实是这么多,后面就不支付了,到此就结束了。也就是说数量可以为负数,但是金额不能为0或者0以下,有什么方法可以绕过这个限制吗,其实并不难,既然可以为负数,只是对金额不能为0或者负数做了限制。我们可以尝试拼接法,利用负数加上正数让他的值变得很低,但是又大于0就可以了,这里利用购物车的结算方法,随机加一些在购物车里。这里为了方便查看数据包,我这边商品的数量选择3,点击立即购买并抓包。

2301_80115097的博客 1528

【算法】哈希表 ( 两数之和 )

给定一个未排序的数组 , 找到数组中的两个元素之和 , 等于给定的 target 值 ;

让 学习 成为一种 习惯 ( 韩曙亮 の 技术博客 ) 4279

DFT实训教程笔记2(bibili版本)- Scan synthesis practice

文章目录Scan synthesis practice 本博文是博主记录DFT实训教程的笔记版本,此笔记并没有对所有的知识进行记录,仅仅以自身的认知水平,来记录了一些部分笔记并加上了自己的理解。 Scan synthesis practice How to design scan clock structure? 假设一块chip里面有好几十个clock domain,如果每一个clock domain都用一个scan clock虽然会非常清晰,但是IO数目肯定不够用。 clock group: 1、no

ciscomonkey的博客 9082

【3D Slicer】阈值法测量肺部病灶体积

利用3D Slicer测量肺容积

SQ的博客 4858

两数之和(LeetCode)——哈希表法(C语言)

上一篇文章留了个引子——用“哈希表”法来解决这个问题。今天,我们来解决一下。为什么用哈希表法?很简单因为它——快!讲解之前我们先来提出几个问题?1)什么是“哈希表”?2)怎么用“哈希表法”来解决这个问题?什么是“哈希表”?(摘自:百度百科)其实 哈希表 就是一种 散列表 ,其英文叫做 “Hash table”,本身就是一种 数据结构 。包含 键值对(key-value),通过一个 key 值来直接访问数据,查找速度快。看完这些仍然一头雾水对吧,下面举个简单的例子,我们应该就会更加理解哈希表。日常生活中都使用

简十三的博客 2624

化学气相沉积CVD工艺中MKS下游排气高速节流阀的国产化替代方案及产品

对标MKS、VAT和CDK等国外公司的下游排气高速节流阀系列产品,本文介绍了相应的国产化替代方案和产品。基于CVD工艺,技术方案将下游流量调节阀变为了下游压力调节阀,并采用分体结构,将调压阀与PID控制器分离,调压阀具备大口径和高速功能,电子气控驱动调压阀快速动作,PID控制器接收真空计信号和控制气控驱动阀,可实现阀门全开时间小于0.1秒。

Shanghai_Eyoung的博客 5259

两数之和——哈希映射求解

两数之和的哈希映射解法、C++

Learner_QUN的博客 211

【数据集】全球大气空气柱平均甲烷(XCH₄)和一氧化碳(XCO)浓度数据集 TROPOMI/WFMD

全球大气空气柱平均甲烷(XCH₄)和一氧化碳(XCO)浓度数据集 TROPOMI/WFMD

WW、forever的博客 387

6、掌握 CorelDRAW:从基础操作到创意绘图

本文详细介绍了CorelDRAW的基础操作与创意绘图技巧,涵盖软件使用注意事项、常用快捷键、全局与局部设置的区别、Dockers面板的高效使用,并通过绘制带星星图案的球实例,逐步演示了对象创建、编辑、复制、分布优化、元素添加、颜色与特效调整等核心功能,最后讲解了作品的保存与输出方法,帮助用户从入门到进阶掌握CorelDRAW的设计流程。

snow3的博客 121

【力扣】1、两数之和

系列文章目录 【力扣】1、两数之和 提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录系列文章目录前言一、pandas是什么?二、使用步骤1.引入库2.读入数据总结 前言 提示:这里可以添加本文要记录的大概内容: 例如:随着人工智能的不断发展,机器学习这门技术也越来越重要,很多人都开启了学习机器学习,本文就介绍了机器学习的基础内容。 提示:以下是本篇文章正文内容,下面案例可供参考 一、pandas是什么? 示例:pandas 是基于NumPy 的一种工具,该工具是为了解决数据分

一个卑微的java开发 1549

近五年体内微/纳米机器人赋能肿瘤精准治疗综述:以 GBM 为重点

摘要 微/纳米机器人在实体瘤治疗领域展现出突破性潜力,通过主动运动能力解决传统纳米药物递送效率低、渗透不足等核心问题。2021-2025年间形成三条技术路线:1) 磁驱、声驱等运动增强递送实现深层渗透;2) 与免疫治疗融合实现原位免疫唤醒;3) 针对胶质母细胞瘤开发跨屏障递送系统。研究重点从单一运动性能转向"运动-分布-疗效"的系统评价,需建立标准化指标评估运动学参数、肿瘤分布均匀性和安全性。未来挑战在于临床转化的可制造性、闭环操控及生物相容性优化,特别是对血脑屏障穿透等复杂场景的系统集

AllenLV的博客 5126

LeetCode1. 两数之和、LeetCode2. 两数相加

本文介绍了两种经典算法问题的解决方案: 两数之和问题: 暴力解法:双重循环遍历数组,时间复杂度O(n²),空间复杂度O(1) 哈希表解法:利用字典存储元素值及其索引,一次遍历完成查找,时间复杂度O(n),空间复杂度O(n) 对比显示哈希表解法在较大数组时效率更优 两数相加问题(链表形式): 算法思路:同时遍历两个链表,逐位相加并处理进位 时间复杂度O(max(m,n)),空间复杂度O(max(m,n)) 包含虚拟头节点处理技巧和进位处理逻辑 提供Python代码实现和示例执行流程图示。

lcreek的博客 898

深度学习工具包 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&#39;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(&#39;DeepLearnToolbox&#39;));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(&#39;state&#39;,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&#39;); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand(&#39;state&#39;,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 = &#39;sigm&#39;;%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, &#39;Too big error&#39;);```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(&#39;state&#39;,0)sae = saesetup([784 100]);sae.ae{1}.activation_function = &#39;sigm&#39;;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)&#39;)% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;;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, &#39;Too big error&#39;);```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x&#39;,28,28,60000))/255;test_x = double(reshape(test_x&#39;,28,28,10000))/255;train_y = double(train_y&#39;);test_y = double(test_y&#39;);%% 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&#39;ll get around 1.2% errorrand(&#39;state&#39;,0)cnn.layers = { struct(&#39;type&#39;, &#39;i&#39;) %input layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 6, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %sub sampling layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 12, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 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, &#39;Too big error&#39;);```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(&#39;state&#39;,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, &#39;Too big error&#39;);%% ex2 neural net with L2 weight decayrand(&#39;state&#39;,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, &#39;Too big error&#39;);%% ex3 neural net with dropoutrand(&#39;state&#39;,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, &#39;Too big error&#39;);%% ex4 neural net with sigmoid activation functionrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;; % 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, &#39;Too big error&#39;);%% ex5 plotting functionalityrand(&#39;state&#39;,0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = &#39;softmax&#39;; % 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, &#39;Too big error&#39;);%% 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(&#39;state&#39;,0)nn = nnsetup([784 20 10]); nn.output = &#39;softmax&#39;; % 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, &#39;Too big error&#39;);```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

Leetcode1-两数之和详解

本文主要讲解了使用暴力法和哈西表法计算Leetcode中两个数之和的题目。

白羊by的博客 1728

OV9734 DATASHEET,完整规格书

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

LeetCode 1 两数之和

Java 编译器不管你逻辑上能不能走到这,方法签名的每一条分支都必须有 return。不写直接编译报错。写个{-1, -1}兜底就行,反正题目保证有解。

殇的不悔 352

LeetCode-1 两数之和(Java实现)

LeetCode两数之和 习题分析 看到这一题,我马上就想到了对该数组进行双层循环,以题目上的数组为例: 第一次循环:2 + 7、2 + 11、2 + 15 第二次循环:7 + 11、7 + 15 第三次循环:11 + 15 换成代码为: for (int i = 0; i < nums.length - 1; i++){ for (int j = i +1; j < nums.length; j++){ if (nums[i] + nums[j] == target)

weixin_47219685的博客 512

LeetCode1 两数之和

return 会直接终止整个方法,不是仅仅跳出循环。使用 HashMap,先判断 containsKey,再 get 取值,防止空指针。哈希表适合「找是否存在另一个数」这类题目,把已经遍历过的数据存起来,避免二次循环。

2301_80294691的博客 227

Leetcode1 两数之和 python两种方法实现

刷Leetcode就如同刷象棋路边摊一样,最开始刷的时候,觉得某一个象棋的路数好奇妙,刷着刷着回过头来看时发现那个招数在自己的眼中变得没那么令人惊讶了,变得稀松平常了。对于一个数组[c1,c2,c3,c4,c5], 可以一组一组的判断,即(c1,c2),(c1,c3),(c1,c4),(c1,c5),分析:给定一个目标数值,需要返回和为目标数值的两个数的下标,而且答案只有一个。第一遍遍历的时候,如果当前数为答案中的第二个数,则target-当前数 则一定位于当前数之前的数组成的哈希集合中。

Chenglin(Ben) Yu's Miracle 1130

深入解析 LeetCode 1:两数之和

摘要:"两数之和"是经典的数组遍历算法题,要求在数组中找出和为指定目标值的两个元素下标。本文详细解析了使用ArrayList的暴力解法:通过双重循环遍历所有元素对(j>i避免重复),将找到的下标存入ArrayList后转为数组返回。该解法时间复杂度O(n²),空间复杂度O(1),适合初学者理解基础数组操作和集合类应用。文章包含完整Java代码、复杂度分析、边界案例验证及实际应用场景,为进一步优化为哈希表解法奠定基础。

2503_93734861的博客 911

Leetcode1:两数之和

Leetcode1:两数之和 思路:哈希表存储 class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i = 0; i < nums.length; i++) { if (map.containsKey(t

zhanghe_zht的博客 189

LeetCode-1-两数之和

题目要求在数组中找到两个数之和等于目标值,并返回它们的索引。提供了两种解法: 暴力枚举法:通过双重循环检查所有可能的组合,时间复杂度O(n²),空间复杂度O(1)。 哈希表法:利用哈希表存储已遍历元素及其索引,每次检查是否存在互补数,时间复杂度O(n),空间复杂度O(n)。 推荐使用哈希表法,因其效率更高。代码实现包括Python、Java和Rust版本,核心思路是计算当前元素的互补值并在哈希表中查找。

weixin_45980775的博客 932

LeetCode 1.两数之和

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。 你可以按任意顺序返回答案。

2301_80211119的博客 459

力扣-1.两数之和

小结:注意不能重复使用,可以一边遍历一边插入。

weixin_46878941的博客 546

力扣-1. 两数之和

力扣-1. 两数之和题目描述示例:Java代码 题目描述 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + ...

Jack魏 590
上一篇: 括号匹配算法
下一篇: 2. 两数相加
NeilZhy
博客等级 码龄11年 175粉丝 145原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值