LeetCode167.Two Sum II - Input array is sorted题解

基于Openrouter的API调用免费大模型 Openrouter 是一个 AI 模型聚合平台,整合了全球 200 多种主流 AI 模型,包括 GPT-4、Claude、Gemini 等,以及国产通义千问、DeepSeek 等。其核心优势是统一的 API 设计,开发者仅需少量代码即可与多个模型交互,还支持自动路由与回退机制。用户可通过 OpenAI SDK 或 LangChain 调用 Openrouter 中的模型。 阅读详情

1. 题目描述

Given an array of integers that is already sorted in ascending order, 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 and you may not use the same element twice.

2. 样例

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

3. 分析

题目描述的很清楚,就是给了一个已经按照升序排列的数组和一个目标值target,我们需要做的任务是在这个数组中找到一对元素的下标,使两个元素之和为target,并且题目已经限定了条件,给定的数组有且只有一对满足条件。
这样就大大缩小了题目的难度。我这里提供了3种方法,其中第一种因为时间复杂度为O(n^2)且没有通过优化,提交的时候直接超时了,第二种是在第一种基础之上做了部分优化,第三种则直接是复杂度为O(n)。

3.1. 方法1 直接二层循环

最直接的就是两层循环,每个元素都和后面的元素相加判断与target是否相等,这种算法很容易想,实现简单,但是时间复杂度为O(n^2),在多个大规模数据的测试样例下直接超时,如下图所示:
这里写图片描述
所有测试样例都过了,证明结果正确,但是卡在了最后那个很多测试数据的样例中,说明两层循环嵌套时间太长。

3.2. 方法2 优化后的二层循环

由于数组是排好序的,我们知道如果当前数组元素numbers[i]要大于等于target的值,那么后面的肯定更大,它们都不会成为结果。于是我们首先先进行判断,将这部分的元素去掉。这种思想是第一种算法的一个优化,好处是参与二层循环遍历的数组元素个数不会那么多,可以节约时间,勉强通过了测试。如图:
这里写图片描述

3.3. 方法3 左右扫描

这种做法类似快速排序的思想:从数组的左右两边同时开始扫描,如果当前两个元素之和等于target,则直接返回结果;如果之和大于target,则说明右边的元素可能比较大,右边的下标向左移动;同理,如果之和小于target,则说明左边的元素可能比较小,左边的下标向右移动。
这里写图片描述

4. 源码

4.1. 方法1 直接二层循环

这个是未通过测试的错误代码:

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        vector<int> result;
        if (numbers.size() <= 1) {
            return {};
        }

        bool isFind = false;
        for (int i = 0; i < (int)numbers.size(); i++) {
            if (isFind == false) {
                for (int j = i+1; j < (int)numbers.size(); j++) {
                    if (numbers[i] + numbers[j] == target) {
                        result.push_back(i+1);
                        result.push_back(j+1);
                        isFind = true;
                        break;
                    }
                }
            }
            else {
                break;
            }
        }
        return result;
    }
};

4.2. 方法2 优化后的二层循环

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        vector<int> result;

        int pos = -1;
        for (int i = 0; i < (int)numbers.size(); i++) {
            if (numbers[i] >= target) {
                pos = i + 1;
                break;
            }
        }
        if (pos == -1) {
            pos = numbers.size();
        }
        bool isFind = false;
        for (int i = 0; i < pos; i++) {
            if (isFind == false) {
                for (int j = i+1; j <= pos; j++) {
                    if (numbers[i] + numbers[j] == target) {
                        result.push_back(i+1);
                        result.push_back(j+1);
                        isFind = true;
                        break;
                    }
                }
            }
            else {
                break;
            }
        }
        return result;
    }
};

4.3. 方法3 左右扫描

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        vector<int> result;
        int left = 0, right = numbers.size()-1;
        while(left != right) {
            if (numbers[left] + numbers[right] == target) {
                result.push_back(left+1);
                result.push_back(right+1);
                break;
            }
            else if (numbers[left] + numbers[right] > target) {
                right--;
            }
            else {
                left++;
            }
        }
        return result;
    }
};

5. 心得

这道题目不难,但是对三种方法进行对比,积累了巧妙算法的思路。

电路设计仿真软件:Mentor Graphics_(11).MentorGraphics软件操作与技巧 / 定义自定义仿真命令// 加载设计文件// 运行仿真// 主函数return 1;return 0;// 自定义设计检查// 获取设计中的所有模块// 遍历所有模块// 检查模块名称是否符合规范if (!// 检查模块中的所有引脚if (!// 主函数main() {通过本节的学习,您应该已经掌握了如何在 Mentor Graphics 中进行二次开发,包括使用 Tcl、C++ 和 Python 进行基本和高级操作。 阅读详情

相关推荐

基于mediapipe的动作捕捉和人物模型的驱动

我实习做这个的时候,当时也找了很多资料,但很多资料都没有讲透,下面我就总结一下自己结合看代码后的感悟,还有一些我认为很重要的点。

qq_58484580的博客 7730

[leetcode]167. Two Sum II - Input array is sorted@Java解题报告

自从实习以后许久没有做算法题了,马上要校招了,重新开始刷题Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.The function twoSum should return ...

zjkC050818的博客 1097

在mdk文件移植太多_XCubeClassB代码 的移植

前言ST在www.st.com官网上提供了针对IEC60730/IEC60335 ClassB认证的软件包。软件包分为三个,分别适用STM8,STM32(基于标准外设库)和STM32(基于HAL库):STM8-SafeCLASSB,STM32-CLASSB-SPL,X-CUBE-CLASSB。本文以X-CUBE-CLASSB为例介绍如何做代码的移植以及经常遇到的问题的解决办法。X-CUB...

weixin_28898707的博客 1841

嵌套vector的使用

形容vector>怎么初始化: 输入m,n m为vector个数 n每个vector中的元素 #include #include using namespace std; int main() { int m,n; cout<<"m="; cin>>m; cout<<"n="; cin>>n;//m个vector 每个vector有n个元素 vector > ivec;

SUMUP 1万+

【机器人开发】四足机械狗(并联结构)URDF建模与Simscape仿真全流程解析

本文详细解析了四足机械狗(并联结构)从URDF建模到Simscape仿真的全流程开发。内容涵盖SolidWorks建模要点、URDF文件导出与优化、Matlab/Simscape环境搭建,以及并联机构特有的运动控制和步态规划实现,为机器人开发者提供了一套完整的解决方案。

weixin_30642561的博客 541

Intel Mobileye EyeQ Ultra:RISC-V架构的L4自动驾驶芯片解析

RISC-V作为开源指令集架构,凭借其模块化设计和可定制特性,正在重塑高性能计算领域。其精简指令集带来的确定性执行时序,特别适合自动驾驶等实时性要求严苛的场景。在异构计算架构中,RISC-V与专用加速器(如NPU、GPU)的协同设计,能显著提升能效比和算力密度。Mobileye EyeQ Ultra采用12核RISC-V集群,结合176TOPS AI加速器和5nm工艺,实现了L4级自动驾驶所需的实时感知与决策能力。这种架构为车载计算平台提供了可扩展的解决方案,同时降低了系统复杂度和BOM成本。

weixin_33245447的博客 434

167. Two Sum II - Input array is sorted

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two number

小猪真的真的真的要减肥了 307

25、BDS-3卫星信号性能与PPP-B2b增强消息完整性分析

本文对BDS-3卫星信号性能及PPP-B2b增强消息的完整性进行了系统分析。评估了MEO、IGSO和GEO卫星的轨道与时钟精度,得出BDS-3总体SISRE为0.25 m,系统完整性可覆盖99.999%的误差。分析表明SIS中断主要由时钟调整和轨道机动引起,个别卫星存在因境外监测受限导致的非计划中断。通过自研解码软件对PPP-B2b增强消息进行采集与解析,实验结果显示BDS-3和GPS的平均历元完整性率均高于98.55%,其中卫星掩码和时钟校正消息的完整性率超过99.8%。研究还发现IGSO卫星相比MEO卫

quiet的专栏 155

Given an array of integers that is already sorted in ascending order, find two numbers such that the

这道题自己思路也对了,就是数组使用出了点问题,然后就是看了别人的代码才改过来,用到匿名数组。 不多说,看代码,   class Solution {     public int[] twoSum(int[] numbers, int target) {     if(numbers==null || numbers.length &lt; 1) return null;         i...

qq_38210187的博客 835

YOLOv5/v7/v8/v9/v10/v11/v12/13目标检测结果解析,超w字精读,IoU、GIoU、DIoU、CIoU、EIoU详细解释,精确率、召回率、AP、mAP与P-R 曲线图深度解析

YOLOv5/v7/v8/v9/v10/v11/v12/13目标检测结果解析,超w字精读,IoU、GIoU、DIoU、CIoU、EIoU详细解释,精确率、召回率、AP、mAP与P-R 曲线图深度解析

在职AI算法工程师,擅长计算机视觉,YOLO目标检测、分割等,擅长web、pyqt界面可视化,好内容持续更新中,来这里跟大家一起学习,共同进步 1445

CKA-CN考试之路----16

所以结合本题,如果有多个文件中都存在同一个值,务必统一,或者修改最后一个次序的文件。中以不同的文件名来区分不同目的的配置会更有利于阅读.就像本题中的。但当有多个文件中存在同一个参数的不同值,最后会生效哪个值?中,但随着配置越来越多不怎么容易阅读.当多个文件同时存在一个参数,但值又不同。有时候我们会将所有内存参数全部写在。确认服务状态(2个红框中的内容)

Q先生 328

Python刷题:简单数组(三)

11.Best Time to Buy and sellStockⅡ    Say you have an array for which the ithelement is the price of a given stock on day i.    Design an algorithm to find the maximum profit.You may complete as many ...

zhtysw的博客 1175

微信开发 - 最新第三方网站接入微信登录、微信支付时,本地 redirect_uri 参数错误导致无法调试的解决方案(微信开放平台)完美解决每次都需要部署到线上测试,在本地使用本地 ip 就能轻松调试

redirect_uri参数错误,微信第三方登录,没有服务器时的测试方法,微信开放平台的回调域名怎么设置为本地域名IP,微信登录微信支付每次调试都需要放到服务器上怎么办,微信登录支付业务在本地调试不了怎么办,在本地怎么测试微信支付和登录,微信第三方登陆本地测试,怎么在本地进行测试,微信回调域怎么设置为本地IP,微信扫码登录redirect_uri参数错误,微信开放平台,微信开放平台开发的第三方登录和支付,vue2,nuxt2,vue3,nuxt3,uniapp,微信开放平台,公众号,微信支付,微信登录授权,

🏆 前端领域优质创作者 8799

LeetCode 167. Two Sum II - Input Array Is Sorted 题解

给你一个下标从 1 开始的整数数组 ,该数组已按 非递减顺序排列,请你从数组中找出满足相加之和等于目标数 的两个数。如果设这两个数分别是 和 ,则 。以长度为 2 的整数数组 的形式返回这两个整数的下标 和 。你可以假设每个输入 只对应唯一的答案,而且你 不可以 重复使用相同的元素。你所设计的解决方案必须只使用常量级的额外空间。示例 1: 示例 2: 示例 3: 解题思路 方法:双指针 思路:复杂度分析: 测试用例 测试用例 1: 输入:输出:输入:输出:输入:输出:本题是双指针的经典应用问题,主要

cannonjinx的博客 2466

数学建模模型总结

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

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

LeetCode力扣 167. 两数之和 II - 输入有序数组 Two Sum II - Input array is sorted 题解代码 JavaScript

问题https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted/ 练习使用JavaScript解答 /** * @param {number[]} numbers * @param {number} target * @return {number[]} */ var twoSum = function(numbers, target) { var i = 0, j = numbers.length-1; .

Coding home - 漂流瓶jz 604

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

LeetCode 167. Two Sum II - Input array is sorted 题解(C++)

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. - The function twoSum should return indices of the two numbers such th

prayyojay的博客 1460

深度学习工具包 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题解-167. Two Sum II - Input array is sorted

题目:Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.The function twoSum should return indices of the two numbers

呜呜哈的博客 906

LeetCode题解(Java实现)——167.Two Sum II - Input array is sorted(两数之和II-输入数组有序)

文章目录Leetcode:167. Two Sum II - Input array is sorted Leetcode:167. Two Sum II - Input array is sorted 题目 &amp;nbsp;&amp;nbsp;Leetcode:167. Two Sum II - Input array is sorted 题目描述 &amp;nbsp;&amp;nbsp;给定一个已经从小到大排好序的整型...

樱木天亥 594

Leetcode PHP题解--D104 167. Two Sum II - Input array is sorted

D104 167. Two Sum II - Input array is sorted 题目链接 167. Two Sum II - Input array is sorted 题目分析 给定一个已经排序好的整数数组,从中寻找两个数字,使其相加之后等于给定的一个数字。 返回这两个数字对应的下...

224

leetcode 167. Two Sum II - Input array is sorted(两数之和 II - 输入有序数组)--Java题解

题目描述 给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。 函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。 说明 返回的下标值(index1和index2)不是从零开始的。 你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。 示例  输入:numbers = [2, 7, 11, 15]...

leyao的博客 532

Leetcode日练笔记11 #350 #167 Intersection of Two Arrays II & Two Sum II - Input array is sorted

#350 Intersection of Two Arrays II Given two integer arraysnums1andnums2, returnan array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result inany order. 解题思路: 还是用回之...

Bittersweet_t的博客 1744

[东哥的leetcode刷题日记] leetcode 167 :Two Sum II - Input array is sorted

leetcode 167 :Two Sum II - Input array is sorted 题目链接: https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted/ 难度: 简单 归类 : 数组操作, 二分查找, hashmap 题目: 给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。 说明:

qq_41847324的博客 401

leetcode-167. Two Sum II - Input array is sorted

167. Two Sum II - Input array is sorted Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. The function two

link98 501

leetcode 167.两数之和-ii-输入有序数组(two sum ii input array is sorted)C语言

leetcode 167.两数之和-ii-输入有序数组(two sum ii input array is sorted)C语言1.description2.solution 1.description https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted/description/ 给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。 函数应该返回这两个下标值 index1 和 index2,其中 index

hsk6543210的博客 276

LeetCode 167. Two Sum II - Input Array Is Sorted【数组,二分;双指针】中等

本文属于「征服LeetCode」系列文章之一,这一系列正式开始于2021/08/12。由于LeetCode上部分题目有锁,本系列将至少持续到刷完所有无锁题之日为止;由于LeetCode还在不断地创建新题,本系列的终止日期可能是永远。在这一系列刷题文章中,我不仅会讲解多种解题思路及其优化,还会用多种编程语言实现题解,涉及到通用解法时更将归纳总结出相应的算法模板。。

memcpy0的博客 343

LeetCode_Array_167. Two Sum II - Input array is sorted两数之和 II - 输入有序数组(C++/Java)

1,题目描述 2,解题思路 3,AC代码 4,解题过程 第一博 采用双指针的方法,左右指针都从最左边(left = 0,right = 1)开始向右迭代:(由于是左右指针从最左边开始,且只要sum<target,就将左右指针同时右移,所以,右指针的位置不会超过答案的右边界位置,因此只需要调整左指针) 指针所指元素之和小于target,左右指针同时右移; 指针所指元素之和大于target,左指针左移; 使用C++测试的效果不太稳定: ...

&再见萤火虫&的博客 216
上一篇: LeetCode240. Search a 2D Matrix II题解
下一篇: LeetCode392.Is Subsequence题解
SYSU_BY
博客等级 码龄14年 96粉丝 63原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值