LeetCode1. Two Sum

在 Windows 上安装 OpenCV – C++ / Python 而且,安装并不是一件容易的事。这些安装程序仅适用于安装 OpenCV for C++。如果您想安装适用于 Python 的 OpenCV,您将在博客后面找到相关信息。在这篇博文中,我们将在 Windows 上安装适用于 C++ 和 Python 的 OpenCV。C++ 安装是在自定义安装 exe 文件的帮助下完成的。而Python的安装是通过Anaconda完成的。从源代码安装 OpenCV 需要花费大量时间。根据您的硬件和安装配置,该过程可能需要 5 分钟到 2 小时不等。 阅读详情
题目链接:

https://leetcode.com/problems/two-sum/

题目描述:

在一个数组(无序)中快速找出两个数字,使得两个数字之和等于一个给定的值。假设数组中肯定存在至少一组满足要求。

题目分析:

我做的是排序加双指针,这个方法不是很好,因为排序会改变对应下标。
参考了这篇博客

http://www.cnblogs.com/ganganloveu/p/3728849.html

用map映射,代码要简洁太多。

<value,index>的映射关系。
遍历numbers,在映射表中寻找target-numbers[i]。
若找不到则将<numbers[i], i>加入映射表。
若找到则结束,返回存储的下标+1和当前下标+1。

代码:

方法1:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
       vector<int> res(2,0);
       map<int,int> m;
       int len=nums.size();
       for(int i=0;i<len;i++){
           if(m.find(target-nums[i])==m.end()){
               m[nums[i]]=i;
           }
           else{
               res[0]=m[target-nums[i]]+1;
               res[1]=i+1;
               return res;
           }
       }
    }
};

方法2:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> nums2(nums);
        sort(nums2.begin(),nums2.end());
        int len=nums2.size();
        int left=0;
        int right=len-1;
        while(left<right){
            if(nums2[left]+nums2[right]==target){
                left=nums2[left];
                right=nums2[right];
                break;
            }
            else if(nums2[left]+nums2[right]>target){
                right--;
            }
            else{
                left++;
            }
        }
        vector<int> res;
        for(int i=0;i<len;i++){
            if(res.size()==2){
                if(res[0]>res[1]){
                    int tmp=res[0];
                    res[0]=res[1];
                    res[1]=tmp;
                }
                return res;
            }
            if(nums[i]==left || nums[i]==right){
                res.push_back(i+1);
            }
        }
    }
};
绕过Cloudflare的两种简便方案 阅读详情

相关推荐

【实战解析】RTL8306MB交换芯片驱动开发中的RMII接口调试陷阱

本文深入剖析了RTL8306MB交换芯片驱动开发中RMII接口的典型调试陷阱。通过一个工业网关项目的实战案例,揭示了因硬件原理图设计疏忽导致TX_EN与CRS_DV信号线错接,从而引发网络“哑火”的根本原因。文章详细展示了使用示波器从时钟、数据到控制信号的系统性排查方法,并总结了关键的设计警示与自查清单,为嵌入式网络开发中的软硬件协同调试提供了宝贵经验。

qqq44的博客 1028

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

在 Ubuntu 22.04 上配置 SonarQube 与 CI/CD 流水线实现自动化代码审查

本文详细介绍了在Ubuntu 22.04系统上配置SonarQube并与CI/CD流水线集成的完整流程,实现自动化代码审查。从环境准备、数据库配置到核心参数调优,再到与Jenkins和GitHub Actions的深度集成,提供了实战技巧和性能优化建议,帮助团队提升代码质量监控效率。

weixin_28829325的博客 258

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

UniApp X 网络请求避坑指南:从 JS 到 UTS 的 JSON 数据处理全解析

摘要:UniAppX开发中处理JSON数据时,UTS强类型特性要求开发者改变JS习惯。本文对比两种主流方案:1)UTSJSONObject通过keypath访问数据,兼容JS但缺乏类型提示;2)type+泛型方案,通过定义数据类型实现强类型校验和智能提示,推荐用于固定数据结构。文章详细演示了两种方式的具体实现、转换方法及实战案例,并提供了类型定义技巧和注意事项,帮助开发者编写更稳定高效的跨平台应用。

归梦工作室 2789

72、海洋地理信息系统:电子海图的全面解析

本文全面解析了海洋地理信息系统中的电子海图技术,从AIS数据的应用、电子海图数据的存储与显示,到电子导航的发展趋势和S-100通用水文数据模型的推广,系统地阐述了电子海图在现代航海中的核心作用及其未来发展方向。

hhh00的博客 252

[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

OpenCV入门(一)Python环境的搭建

因为有点Python基础,并且Python是比较好入门的编程语言,所以,机器视觉后面打算在Python这个平台下进行。

小幽余生不加糖 8121

LeetCode 1. Two Sum 题解

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

cannonjinx的博客 4192

MicroCap声学仿真介绍(三)-人耳的频率响应

这里需要注意的是,24mm我们会填为”24m”,这里的“m”是毫的意思,24m意思是24e-3,同理7.4mm我们可以填为7.4m,意思是7.4e-3。MicroCap声学库中,已内置“声源”模块和“管”模块,我们需要调用这两个模块,并用连接线将这两个模块连接到一起,完成仿真工作。上图中第一个图是在管的一端输入1Pa(94dBSPL)的信号,管的另一端的不同频率的声压大小的仿真结果。上述的结果跟我们的常识也是符合的。换言之,我们要仿真的目的是在管的一端加1pa的声压时,管的另一端不同频率下的声压分布。

山无忧的博客 1471

Yolo8行人车辆目标检测实战分享 完整项目代码可直接运行

Yolo8行人车辆目标检测实战分享 完整项目代码可直接运行

1294

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

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

maoersong的专栏 358

Ubuntu 系统下安装 OpenClaw(原 Clawdbot)的详细指南

Ubuntu 系统下安装 OpenClaw(原 Clawdbot)的详细指南

Science prince的博客 3535

Leetcode ☞ 1. Two Sum ☆ 【Hashmap】

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

Dr_Unknown的博客 983

深度学习工具包 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")

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

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

SIMATIC S7-1200, S7-1500 PID 控制[手册]

SIMATIC S7-1200, S7-1500 PID 控制[手册]

LeetCode 1 Two Sum——在数组上遍历出花样

本文始发于个人公众号:TechFlow 今天是周末,和大家一起来看一道算法题。这道题是大名鼎鼎的LeetCode的第一题,也是面试当中非常常见的一道面试题。题目不难,但是对于初学者来说应该还是很有意思,也是一道很适合入门的算法题。 废话不多说,让我们一起来看看题目吧。 Given an array of integers, return indices of the two numbers su...

TechFlow的博客 230

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

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 the same...

Smiling_Wang的博客 267

【LeetCode with JavaScript】1.Two Sum

原题网址:https://leetcode.com/problems/two-sum/ 难度:Easy 题目 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。 Example: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 ...

zwkkkk1的博客 1024

java two sum 讲解_【LeetCode 力扣】1. Two Sum 两数之和 Java 解法

LeetCode的第一题,英文单词书中 Abandon 一般的存在,让我们来看一下题目:Given an array of integers, returnindicesof the two numbers such that they add up to a specific target.You may assume that each input would haveexactlyo...

weixin_36072221的博客 217

LeetCode 1.Two Sum map 初次使用Markdown*****

外传 经过室友推荐blog转战Markdown编辑,初次使用还觉得挺不方便需要那么多快捷键,不如鼠标点的快。今天这一篇文章才写一半就觉得很好用,就像电脑操作用鼠标点击和windows快捷键操作一样爽,在此向还没转战的朋友推荐,顺便练习自己的操作。 不方便的是代码高亮显示不好。 参考快速上手 记录插入链接格式 题目 题意 注意 思路1 代码

老夫编代码就是一把梭 1144

LeetCode力扣 1. 两数之和 Two Sum 题解代码 JavaScript

问题 https://leetcode-cn.com/problems/two-sum/ 练习使用JavaScript解答 /** * @param {number[]} nums * @param {number} target * @return {number[]} */ var twoSum = function(nums, target) { var i, j = nums.length-1, sum; var num2 = []; for(i=0;i&lt

Coding home - 漂流瓶jz 590

[leetCode-1]two-sum (java version)

[leetCode-1]two-sum 欢迎使用Markdown编辑器 你好! 这是你第一次使用 Markdown编辑器 所展示的欢迎页。如果你想学习如何使用Markdown编辑器, 可以仔细阅读这篇文章,了解一下Markdown的基本语法知识。 新的改变 我们对Markdown编辑器进行了一些功能拓展与语法支持,除了标准的Markdown编辑器功能,我们增加了如下几点新功能,帮助你用它写博客: ...

fruitful1989的博客 153

Leetcode学习笔记:#1 Two Sum

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 yo...

ccystewart的博客 209

【仅用于个人整理记忆】LeetCode算法题之1. Two Sum(easy)

声明: 如标题所示,因本人为AI路上的新手,文章仅用于辅助个人的整理记忆,理解难免有偏差之处,都是个人拙见,如给其他同僚造成困扰,还请见谅,非常非常非常欢迎私信共同讨论,共同进步 题目描述如下: Given an array of integers, return indices of the two numbers such that they add up to a specific targ...

DaMoWangZQ的博客 272

【Leetcode】1. Two Sum

题目地址: https://leetcode.com/problems/two-sum/ 在一个数组中寻找两个数其和为给定的target,返回这两个数的下标。 思路是用一个哈希表存储数字和其对应的下标,一旦发现target与某个数之差在哈希表里已经存在,就返回两个下标。代码如下: import java.util.HashMap; import java.util.Map; public cla.........

数学、算法爱好者的博客 163
上一篇: LeetCode64. Minimum Path Sum
下一篇: PAT1056 Mice and Rice (25)
_IanXiao
博客等级 码龄12年 84粉丝 241原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值