博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Two Sum II - Input array is sorted
阅读量:5344 次
发布时间:2019-06-15

本文共 2236 字,大约阅读时间需要 7 分钟。

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.

Input: numbers={2, 7, 11, 15}, target=9

Output: index1=1, index2=2

 

已经排好序了,当然会想到二分搜索,不过我想到的比较蠢。。。

1 class Solution { 2 public: 3     vector
twoSum(vector
& numbers, int target) { 4 5 int n = numbers.size(); 6 vector
res; 7 8 for (int i = 0; i < n; ++i) 9 {10 int solu = target - numbers[i];11 int lo = 0, hi = n - 1;12 while (lo <= hi)13 {14 int mid = lo + (hi - lo) / 2;15 16 if (solu < numbers[mid])17 {18 hi = mid - 1;19 }20 else if (solu > numbers[mid])21 {22 lo = mid + 1;23 }24 else25 {26 res.push_back(i + 1);27 if(numbers[i]==numbers[mid])28 {29 res.push_back(i + 2);30 return res;31 }32 res.push_back(mid + 1);33 return res;34 }35 }36 }37 }38 };

贴上一个两端逼近的吧,更加简洁清晰:

1 vector
twoSum(vector
& numbers, int target) { 2 3 int l = 0; 4 int r = numbers.size() -1; 5 while(l < r){ 6 if(numbers[l] + numbers[r] == target){ 7 vector
res{l+1,r+1}; 8 return res; 9 }10 else if(numbers[l] + numbers[r] > target){11 r--;12 }13 else{14 l++;15 }16 }17 }

 

转载于:https://www.cnblogs.com/jiadyang/p/8604677.html

你可能感兴趣的文章
FSCapture截图软件注册码
查看>>
NewBluePill源码学习 <一>
查看>>
从Android看设计模式
查看>>
51nod 1083 矩阵取数问题【动态规划】
查看>>
分数四则运算器
查看>>
xml转义技术
查看>>
取消PHPStorm注释斜体
查看>>
POWERSPLOIT-Exfiltration(信息收集)脚本渗透实战
查看>>
Microsoft Dynamics CRM 2013 安装过程 图解
查看>>
存储过程的输出接受强类
查看>>
对象 -----JavaScript
查看>>
百般武艺为哪般---再谈业务域的核心地位
查看>>
C#尝试读取或写入受保护的内存,相机SDK指针托管内存转换图像问题
查看>>
作业1 对该课程期望
查看>>
上传人员照片
查看>>
ST表
查看>>
day2----python标识符
查看>>
HBase教程
查看>>
thinkphp 检测上传的图片中是否含有木马脚本
查看>>
sharepoint 2010 的office web app与Office客户端
查看>>