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, 阅读详情
**1. Two Sum(Easy)**

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 not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,

return [0, 1].

public static int[] TwoSum1(int[] nums, int target)
        {
            for (int i = 0; i < nums.Length; i++)
            {
                for (int j = i + 1; j < nums.Length; j++)
                {
                    if (nums[i] + nums[j] == target)
                    {
                        return new int[] { i, j };
                    }
                }
            }
            return null;
        }
        public static int[] TwoSum2(int[] nums, int target)
        {
            List<int> list = new List<int>();
            for (int i = 0; i < nums.Length; i++)
            {
                list.Add(nums[i]);
            }
            for (int j = 0; j < nums.Length; j++)
            {
                if (list.Contains(target - nums[j]) && list.IndexOf(target - nums[j]) !=  j)
                    return new int[2] { j, list.IndexOf(target - nums[j]) };
            }
            return null;
        }
        public static int[] TwoSum3(int[] nums, int target)
        {
            List<int> list = new List<int>();
            for (int j = 0; j < nums.Length; j++)
            {
                list.Add(nums[j]);
                int completation = target - nums[j];
                if (list.Contains(completation) && list.IndexOf(completation) != j)
                    return new int[2] { j, list.IndexOf(completation) };
            }
            return null;
        }
Leetcode: 1.Two Sum 两数之和 Two Sum 两数之和 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。 输入: nums = [2, 7, 11, 15], target = 9 输出: [0, 1] 因为 nums[0] + nums[1] = 2 + 7 = 9 ... 阅读详情

相关推荐

LeetCode::Two Sum C语言

题目 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,

世界是兔子的 1万+

从 Two Sum 开始: LeetCode100

Two Sum 其实是很多算法题的原型。很多后续题目都是它的变形,比如:Two Sum IIThree SumFour Sum所以理解这题,其实是在建立Hash 思维的基础。重新刷 Two Sum 的过程让我意识到:算法不是记住解法,而是建立一种思考模式。当看到一个数时,要习惯性问自己:我真正需要找的,是不是?当这种模式形成之后,很多题目就会变得自然很多。有时候回头看最基础的题,反而会有新的理解。这也是刷算法最有意思的地方。

qq_39899644的博客 534

Veristand simulink 集成 simulink 非正版如何处理

1、安装 veristand model Generation Support add-on。matlab 安装veristand model support 记录。下载 以后 如果非正版matlab 直接拖命令行执行。下载后直接命令行执行即可。

flik9527的博客 598

《LeetCode》:Two Sum

《LeetCode》:Two Sum昨天刚说的准备去刷《程序员面试金典》上面的题,但是看了下那本书上面的题,感觉都没有什么意思,因此也就打算来刷了leetCode上面的题了。刷题的顺序选择了按照顺序来刷。今天开始了第一题:Two Sum 题目如下: 意思就是:在一个整型数组中,寻找两个数等于一个定值,返回这个数在数组中的下标,要注意的是:下标不是从0开始的。《剑指Offer》上也有类似

wojiushimogui的博客 811

若依RuoYi文件上传漏洞实战:如何安全配置/profile/upload路径(附避坑指南)

本文深入解析若依RuoYi框架中/profile/upload路径的文件上传漏洞,提供详细的安全配置方案和实战指南。通过权限修正、输入验证强化和存储隔离等多层防御策略,有效防范未授权访问和恶意文件上传风险,保障系统安全。

pink的博客 778

汽车底盘技术解析:从悬架调校到智能化,如何评价国产车底盘实力

汽车底盘作为决定车辆驾驶质感、安全性和耐久性的核心系统,其技术内涵远不止于悬架结构。从行驶系、转向系到制动系的协同工作,底盘调校是一门融合机械原理与工程实践的艺术。在电动化与智能化浪潮下,底盘技术正经历从被动适应到主动响应的变革,CDC可变阻尼减震器和空气悬架等技术的应用,让底盘具备了通过OTA升级实现性能优化的可能。国产汽车品牌如奇瑞、吉利等,通过平台化架构研发与调校经验积累,正推动底盘技术从“能用”向“好用”乃至“塑造独特驾驶风格”迈进。理解底盘技术,需超越简单的结构对比,关注其在实际路况中的滤震性、支

weixin_34413103的博客 384

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

从硬件到软件:深度解析D435i USB SCP overflow错误的根源与解决方案

本文深入解析Intel RealSense D435i相机在ROS环境下常见的'USB SCP overflow'错误,特别是与`control_transfer`相关的错误提示。从硬件配置到软件优化,详细介绍了如何通过调整USB接口、优化`rs_camera.launch`参数、更新固件驱动等方法解决数据传输溢出问题,提升设备稳定性和性能。

yy01234的博客 771

【Java版】LeetCode 力扣第 1 题:两数之和 (two sum)

题目描述 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] 题目解析 使用查找表来解决该问题。 设置一个 map 容器 record 用来记录元素的值与索引,然后遍历数组 nums

代码时光 384

RK3588开发笔记-Buildroot编译Qt5WebEngine-5.15.10

Rockchip RK3588是一款强大的多核处理器,广泛应用于边缘计算、人工智能、嵌入式系统等领域。为了在RK3588上运行自定义的Linux系统,并使用Qt5WebEngine进行Web内容渲染,Buildroot是一个非常合适的工具。本文将详细介绍如何使用Buildroot编译并配置Qt5WebEngine-5.15.10。Qt5WebEngine是Qt框架中的一个模块,它提供了一个功能强大的Web浏览器引擎,允许开发者在Qt应用程序中嵌入和显示现代网页内容。

flypig has a dream! 1157

Claude Desktop新功能:让非技术人士也能自主编程

摘要: Anthropic近日在Claude桌面应用中集成了Claude Code功能,显著降低了非技术用户的使用门槛。Claude Code作为代理式编程工具,支持多任务并行处理、Git隔离和可视化会话管理,无需命令行操作即可实现代码调试、重构等复杂任务。新增的“计划模式”通过先分析后执行的流程,确保安全性,使产品经理、数据分析师等非开发者也能参与技术工作。这一更新标志着AI技术正打破专业壁垒,让领域专家无需编码背景即可利用高级工具,推动技术民主化。

独立开发,substack顶级编辑 1540

LeetCode:Two Sum

LeetCode解题记录

vivianXuejun的博客 372

BMD101传感器协议解析与STM32实现(LCD显示波形)

1 前言 BMD101传感器是神念科技开发的心电传感器。目前有一些商家开发了BMD101传感器模块,基本上都是利用蓝牙直接传输数据到PC或手机端。而本文介绍通过串口将数据传送给单片机,并在单片机上完成数据解析和心电波形LCD显示的功能。 2 通信协议解读 BMD101 通过 UART 接口通信。这是一个标准的 UART 接口,定义为 1 个起始位,8 个数据位,1 停止位格式,波特率 57600。 串口输出的数据包格式如下: 包括Header(帧头)、data payload(数据有效载荷)、CRC校验

weixin_44509533的博客 9287

LeetCode: Problem 1, Two Sum

LeetCode: 2 sum 题目链接:https://leetcode.com/problems/two-sum/ 作为一名学院小学渣,被dalao推荐来写leetcode,第一题就耗费了我好久时间,想尽量努力长期刷下去,就有了长期写博客的想法,希望自己能在这里坚持下去吧。 ...

swordpj的博客 198

量化交易 米筐 多因子合成(回测中使用)

多因子合成 1、因子合成 将一些相关(高、低)的因子合成一个因子 方法: 使用PCA方式(使用于较强相关性) 2、核心代码 将因子 inc_revenue_ttm 和 operating_revenue_growth_ratio_ttm 合成为一个因子 inc_operating from sklearn.decomposition import PCA pca = PCA(n_components=1) # 因子合并 fund['inc_operating'] = pca.fit_transform(fu

廷益_飞鸟的博客 1062

深度学习工具包 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 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 each input would have exactly one solution. Example: Giv

生而彷徨 1619

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

Leetcode: 167. Two Sum II - Input array is sorted

Leetcode: 167. Two Sum II - Input array is sorted 超时的代码: public class Sum22 { public int[] twoSum(int[] numbers, int target) { int result[] = new int[2]; ...

哎呀妈呀脑壳疼脑壳疼 97

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

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 ta

Magi Su的技术回收站 8441

LeetCode面试常考题:Two Sum

作者:Linux猿 简介:优快云博客专家,C/C++、面试、刷题、算法尽管咨询我,关注我,有问题私聊! 关注专栏:LeetCode面试常考100题(优质好文持续更新中……) 一、题意 给定一个整数数组 nums 和一个整数 target ,找到数组里的两个数的和等于 target,返回这两个数在数组中的下标,假设每个输入都只有一个解决方案,并且不能两次使用相同的元素。可以按任何顺序返回答案。 注意:数组无序。 二、测试样例 输入:nums = [2,7,11,15], target ...

Muti-Agent 6366

Leetcode: Two Sum — python

leetcode questions — pythonQuestionAnswernotes Question 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 ...

weixin_42988124的博客 229

【LeetCode】解题1:Two Sum

LeetCode解题 1:Two Sum Problem 1: Two Sum [Easy]Solution (Java)修改过程 Problem 1: Two Sum [Easy] Given an array of integers, return indices of the two numbers such that they add up to a specific target. Yo...

Fayedily的博客 249

leetcode: 1 Two Sum

最近开始刷leetcode, 这是第一题,没什么复杂的直接上代码好了题目是: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 sol...

DinnerHowe的博客 753

1. 两数之和 [leetcode 1: Two Sum]

1. 两个数的和 [leetcode 1: Two Sum] 原题链接 https://leetcode.com/problems/two-sum 老王的解法链接 https://github.com/simplemain/leetcode/blob/master/1/analysis.md 难度 ★☆☆☆☆ 标签 循环 / 二分搜索 / 排序 / 哈希 题目描述 输入一个整数数组和一个整数, 要...

简单的老王 368

JS斩杀LeetCode(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 each input would have exactly one solution, and you may not use

清风的博客 1655
上一篇: 第一周 ARTS
下一篇: LeetCode:Add Two Numbers
Ken_Li_Lsq
博客等级 码龄14年 22粉丝 61原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值