LeetCode——Two Sum

leetcode解题笔记:Two sum系列解题思路 Two Sum 3Sum 3Sum Closest Two SumGiven an array of integers, return indices of the two numbers such that they add up to a specific target.You may assume that each input would have exactly one solution, 阅读详情

LeetCode——Two Sum

LeetCode上第一题:


题目如下:

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

题目翻译:


给定一个整数数组和一个目标整数,我们要做的是从这个整数数组中找出两个数,满足这两个数的值相加等于目标整数,返回这两个数的下标(从一开始)
这里假定每给一个目标整数总能找到这样的两个数,即不考虑不存在的情况。  还要注意到这种情况,即这两个数是不同的(题目中隐含的)例如:给定一个
整数数组:numbers = { 2 3 4 } ,target = 6 返回的结果不是 2 ,2  而是 1, 3尽管 3+3 = 6

解题思路——第一种方法:


我们很容易想到的一个解法是只要遍历所有的元素,判断两个数的和是不是等于target就可以了,更简化一下是选定第一个数后,第二个数从第一个数的后一个数进行选取
或者这样想——选取第一个数之后,用target减去这个数,看得到的值是否在数组中。这样我们就得到了第一种方法:
<span style="font-size:14px;">vector<int> twoSum(vector<int>& nums, int target)
{
	vector<int> index;
	vector<int>::iterator iter = nums.begin();
	vector<int>::size_type ix = 0;
	vector<int>::const_iterator result;
	for(ix=0;ix<nums.size();++ix)
	{
		result = find(iter+ix+1,nums.end(),target-nums[ix]);
		if(result!=nums.end())
		{
			index.push_back(ix+1);
			index.push_back(result-iter+1);
			break;
		}
	}
	return index;
}</span>

这种方法很简单,但很遗憾leetcode不接受这个复杂度的算法,我们需要一种更快的算法。

解题思路——第二种方法:

这里我们需要使用C++ STL中的map容器 
首先我们把整数数组的每一个值作为map容器的第一个参数输入,其对应的下标作为第二个参数输入,然后进行循环遍历数组,对于给定的target只需检测target减去选取的第一个数的值是否存在于map容器中。这样的话我们就得到了一个O(n)的算法。
<span style="font-size:14px;">vector<int> twoSum2(vector<int>& nums, int target)
{
	vector<int> index;
	map<int,int> mp;
	for(int i=0;i<nums.size();++i)
	{
		mp[nums[i]] = i;
	}
	map<int,int>::iterator iter;
	for(int j=0;j<nums.size();++j)
	{
		iter = mp.find(target-nums[j]);
		if(iter!=mp.end())
		{
			if(j==iter->second)
				continue;
			index.push_back(j+1);
			index.push_back(iter->second+1);
			break;
		}
	}
}</span>





LeetCode算法详解(一)--Two Sum 这个题目的目的就是给定数组以及目标和,找出数组中和为给定目标的两个数并且输出,要求是每个数只能使用一次,且输出的为两个数在数组中的位置。比较容易想到的方法是遍历数组中的所有数字,此种方法时间复杂度比较高O(n^2),代码如下:class solution{ public: int[] twosum(int[] nums,int target){ int len = nums.length;... 阅读详情

相关推荐

android+音乐节拍检测,科学网—音乐节拍跟踪或音乐节拍检测软件,LilyBeats alpha - 石自强的博文...

我们设计并实现了一种用于实时跟踪音乐节拍的软件。该软件可以用于智能灯方案提供商,为其提供灯光随音乐变化的核心解决方案。首先给出软件的下载链接:或者音乐节拍是乐曲中表示固定单位时值和强弱规律的组织形式,亦称拍子。它有两个特性:周期性和连续性。节拍周期性表现为节拍结构,是乐曲中周期性出现的节奏序列。节拍连续性表现为音乐的平均速度,其单位为bpm(beat per minute每分钟音乐节拍的个数)。音...

weixin_39571403的博客 1401

LeetCode 1. Two Sum 题解

本题是算法的经典入门问题,主要考察对哈希表的理解和应用。通过使用哈希表,我们可以将时间复杂度从 O(n²) 降低到 O(n),大大提高了算法的效率。哈希表的核心思想是:通过哈希表来存储已经遍历过的元素及其下标,这样当我们遍历到当前元素时,可以在 O(1) 的时间复杂度内检查目标值与当前元素的差值是否已经存在于哈希表中。这种方法不仅适用于两数之和问题,还可以应用于许多其他需要快速查找元素的场景。掌握哈希表的使用,对于解决这类问题非常重要。

cannonjinx的博客 4192

从波形图到参数调优:一次无感BLDC电机启动失败的深度解析

本文深入解析无感BLDC电机启动失败案例,通过波形分析揭示参数不匹配和IPM保护机制触发等关键问题。详细探讨了过零点检测、PWM周期设置及强拖参数调优的底层逻辑,并分享IPM模块保护机制与实战调优技巧,最终实现99.98%的启动成功率。

weixin_29182481的博客 819

ACM之LeetCode中Two Sum

题目信息: Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution. Example: G

Microstrong 864

疫情数据分析的“核武器”!JHU CSSE COVID-19数据集超深度解析与实战指南(附代码)

在面对这场没有硝烟的战争时,除了医护人员在前线与病毒搏斗,还有一群默默的英雄——数据科学家和分析师,他们利用手中的“数据武器”,昼夜不停地监测、分析、预测疫情走势,为政府决策、资源调配、公众科普提供了至关重要的支撑。同时,由于某些国家(如美国、加拿大、澳大利亚、中国等)的数据细化到省/州级别,为了得到国家层面的总数据,我们需要按国家和日期进行聚合。正是在这样的背景下,经过这些步骤,我们已经得到了一个包含了累计数据、每日新增数据和活跃病例数的完整数据集,可以开始进行深入的分析和可视化了!

wylee的博客 1165

鸿蒙读书笔记1:《鸿蒙操作系统设计原理与架构》

GUI、 语 音 控 制 方 式 的 VUI(Voice User Interface, 语 音 用 户 界。电话、多媒体、DFX、MSDP(Multimodal Sensor Data Platform,多。面)、手势/姿态控制的CVUI(Computer Vision User Interface,计算。KAL(Kernel Abstract Layer,内核抽象层)通过屏蔽多内核差异,JavaScript、C、C++等多语言的用户程序开发框架,以及UI框架、

jackyrongvip的专栏 2449

LeetCode刷题笔录 Two Sum

Two Sum Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the

likecool21的专栏 1万+

分析国外几款主流蜜罐产品看欺骗诱捕技术的应用脉络

网络安全的本质是攻防对抗,更本质的其实是人与人心智与技术的全面较量。 欺骗诱捕技术作为攻防对抗技术中比较特殊的技术,能够使防守方更多掌握对抗中的主动权,诱导攻击,迫使攻击者耗费精力的同时,留下丰富的攻击信息。究其本质,欺骗诱捕技术更深层次考验的不止是技术的能力,还有对于攻击者作为人的理解。 国外主流蜜罐产品分析 根据MarketsandMarkets《欺骗技术市场规模、份额和2021年全球市场预测》中提到的欺骗诱捕技术全球主要供应商及产品,我们分析了几款国外主流的蜜罐产品,希望更清晰看到欺骗诱捕技术应

cdyunaq的博客 1307

LeetCode 1 Two Sum题解

题目地址:https://leetcode.com/problems/two-sum/ 1. Two Sum 难度:简单 Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that e

赞美月亮的专栏 665

Win10插网线显示未识别网络的三种解决方法

本文介绍了三种解决Win10插网线显示未识别网络问题的方法:更新或重启网络设备驱动程序、重置Winsock目录、启用Network Setup Service服务。这些方法都是基于常见的网络问题和解决方案而设计的,适用于大多数Win10用户。如果你遇到了这一问题,可以按照上述步骤进行操作,相信一定能够找到解决问题的方法。需要注意的是,在进行任何操作之前,请务必备份重要数据以防万一。此外,如果你对计算机硬件或软件不熟悉,建议寻求专业人士的帮助以避免造成不必要的损失。

nntxthml的博客 6773

GPU 资源池化云平台解决方案​

定义与特点Kubernetes是一个开源的容器编排和管理平台,通过提供自动化和声明式的方式来部署、扩展、维护和运行应用程序。它支持跨多个主机和集群部署容器,确保应用程序的高可用性和可扩展性。Kubernetes提供了丰富的功能和插件,允许用户根据自己的需求进行定制和扩展。架构与组件控制平面(Control Plane):负责集群的决策(如调度)和集群状态的检测与响应。

ZhangJiqun&191cm&85kg 1161

LeetCode--Python解析【Two Sum】

题目:方法1:暴力算法,直接循环套循环。class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ result = list(...

ZJRN1027的博客 4896

第三节:Vben Admin登录对接后端login接口

上一节,我们梳理的Vben Admin登录功能接口的逻辑,本节开始正式开启后端的开发后端我们采用Python的Flask项目,Flask-SQLAlchemy管理数据库模型,Flask-Migrate进行模型迁移。参考版本如下:Flask3.0.23.1.1本节,我们已经开启的后端的开发,因为是主要介绍Vben Admin的登录逻辑,所以Flask开发这里只截取了部分主要代码。

cuiwin的专栏 4190

[LeetCode] No.1 Two Sum

“做程序员太辛苦了,我想换行……我该怎么办?” “敲一下回车。” Two Sum(两数之和) 题目: Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would...

但行好事 莫问前程 348

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

Leetcode力扣 1 | 两数之和 Two Sum —— python

Leetcode力扣 1 | 两数之和 Two SumQuestionAnswerBrute Force 暴力求解法HashTable 哈希表法 该系列以提高编程能力、学习数据结构与算法为目的 编程语言:python Question 给定一个数组nums、一个目标target值(以下简写成nums、target) 我们的目的是在nums中,找到两个元素,使其相加等于target值,然后返回这两个元素在nums中的索引,就是数组下标。 题目中给了三个示例: 第一个返回下标0和1,因为2与7的和为9

idl1ng的博客 1140

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

【Leetcode】001 Two Sum

【Leetcode】001 Two Sum题目Given an array of integers, return indices of the two numbers such that they add up to a specific target.You may assume that each input would have exactly one solution, and you m

LYZ 4829

深度学习工具包 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 01 Two Sum

Leetcode 01 Two Sum ##Description 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] ##solution metho...

jqc_ustc的博客 257

Leetcode ☞ 1. Two Sum ☆ 【Hashmap】

给一数组和一target数,有两个元素的和为target。求这两个元素的下标的和。

Dr_Unknown的博客 983

leetcode: 哈希——two-sum,3sum,4sum

1). two-sum Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add ...

156

Leetcode 1 Two Sum

Question : Two Sum Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may...

嗨~ 172

【Python刷力扣hot100】1. Two Sum

本文介绍了在整数数组中寻找两数之和等于目标值的两种解法。暴力搜索法通过双重循环遍历所有组合,时间复杂度O(n²),空间复杂度O(1)。哈希表法则利用字典存储已遍历元素,以空间换时间,时间复杂度降至O(n),空间复杂度O(n)。两种方法均能有效解决问题,但哈希表法在效率上更优。文章包含Python代码示例和复杂度分析。

tao355667 907

力扣Leetcode1 | 两数之和(Two Sum)

暴力法、一次哈希表和两次哈希表法 https://blog.youkuaiyun.com/zhushaojiecumt/article/details/102846196 视频: https://www.bilibili.com/video/BV1Li4y1E7gT?p=1 双指针法 如果列表是无序的,需要先排序,使用双指针,分别指向头、尾。如果两数之和大于target,尾指针前移,如果两数之和小于target,首指针后移。 class Solution: def twoSum(self, nums: List

maoersong的专栏 358

【LeetCode】 LC10001 两数之和(Two Sum),力扣第一题。

本文介绍了解决"两数之和"问题的两种方法及核心知识点。暴力枚举法通过双重循环遍历数组,时间复杂度O(n²),空间复杂度O(1);哈希表法利用空间换时间,存储已遍历元素及其索引,时间复杂度O(n),空间复杂度O(n)。核心知识点包括:数组(随机访问快但大小固定)、哈希表(快速查找)、时间/空间复杂度分析及空间换时间策略。哈希表法更高效,适合数据量大的场景,体现了用额外空间换取时间优化的设计思想。

thinkgame的博客 1315

LeetCode 1. Two Sum(c语言实现)

问题描述: 给定一个数组,找出两个元素,其相加等于一个给定的目标值,返回这两个元素的索引值。 Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have...

caotuo_csdn的博客 1296
上一篇: 全排列算法研究
下一篇: LeetCode——Add Two Numbers
cassiePython
博客等级 码龄12年 303粉丝 135原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值