描述

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

分析

用的是二分的思想。

考虑到输入的是递增的有序数组,且有且仅有一组输出结果,因此可以用两个变量,分别从数组起始处i和末尾处j开始,如果两个数相加等于target,就返回这两个下标;如果相加大于target,那么就减小j的值,如果相加小于target,那么就增加i的值,直到找到为止。

代码如下:

class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
/*
Time exceeded code
int i = 0;
int len = 0;
vector<int>ret;
for(auto it = numbers.begin(); it != numbers.end(); ++it){
int another = target - *it;
auto index = find(it + 1,numbers.end(),another);
if(index != numbers.end()){
len = distance(it,index);
break;
}
++i;
}*/ int i = 0,j = numbers.size() - 1;
while(i < j){
if(numbers[i] + numbers[j] == target){
vector<int>ret = {i + 1,j + 1};
return ret;
}else if(numbers[i] + numbers[j] > target)
--j;
else
++i;
} }
};

最新文章

  1. asp.net 手工调用 WS(Get)方法:
  2. 初识Oracle数据库的基本操作
  3. Javascript 多浏览器兼容性问题及解决方案
  4. 在中心交换机前加入多wan口路由,华为中心交换机的学习
  5. 点击劫持(CLICKJACKING)与X-FRAME-OPTIONS HEADER
  6. 万向节死锁 gimbal lock
  7. ural 1150. Page Numbers
  8. Windows7防火墙服务无法启用怎么办
  9. 《sed的流艺术之三》-linux命令五分钟系列之二十三
  10. openStack core service Components Ins shell scripts and simple provision
  11. 免费利用网页版谷歌翻译实现任意语言转换php版
  12. nginx配合IIS实现简单负载均衡
  13. MySQL: Integer &amp; String types
  14. 仿iphone快速导航悬浮球
  15. Android ViewManger解析 从ViewRoot 源码分析invalidate
  16. c# async和await 用法(阻塞与不阻塞)
  17. 唤醒实验(java
  18. C#连接数据库插入数据
  19. Pytorch中的torch.cat()函数
  20. HTTP协议头注射漏洞实例

热门文章

  1. PowerBuilder学习笔记之调用事件和函数
  2. LOJ3049 [十二省联考2019] 字符串问题 【后缀自动机】【倍增】【拓扑排序】
  3. The Preliminary Contest for ICPC Asia Xuzhou 2019 E XKC&#39;s basketball team [单调栈上二分]
  4. Netty服务端创建流程及组件职责
  5. 使用其他身份运行计算机(DOS命令)
  6. Access-Control-Max-Age
  7. Mybatis之日志工厂
  8. rabbitmd
  9. Django Rest framework的限流实现流程
  10. Eclipse-错误集