167. Two Sum II
来源:互联网 发布:ubuntu修改hosts翻墙 编辑:程序博客网 时间:2024/06/06 06:30
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
翻译:给定一个数组,这个数组已经排序好了,找到两个数字,使得他们相加的和是一个特定的目标数。
函数twoSun返回两个数字的下标,其中下标1必须小于下标2(返回的数从小到大排序)
可以假设每个输入的目标值都只有一个解决方案,并且不能使用相同的元素相加两次。
分析:只有一个解决方案,也就意味着输出的数组中只有两个数。
class Solution{public:vector<int> twoSum(vector<int>& numbers,int target){vector<int> num;int len=numbers.size();int i=0,j=len-1;while(i!=j){if(numbers[i]+numbers[j]==target){num.push_back(i+1);num.push_back(j+1);}else if(numbers[i]+numbers[j]>target)j--;elsei++;}return num;}};
阅读全文
0 0
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- matlab基础(2)
- 汉诺塔(Hanoi)问题递归&非递归的C++实现及总结
- 十进制转十六进制的C实现
- 【HDU 1003】 Max Sum
- <C++ Primer_5th>习题_3.22
- 167. Two Sum II
- <C++ Primer_5th>习题_3.23
- Spring框架-第一弹
- ios-frame和bounds
- LinkList_Stack(链式栈)
- 第2篇 SercureCRT使用root远程登录ubuntu16.04
- <C++ Primer_5th>习题_3.24
- CodeForces
- <C++ Primer_5th>习题_3.25