Given an array of integers, 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.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
感觉这个题限制太多了,可能会存在重复关键字,且可能是两个重复关键字之和等于target,这种情况下,只能一个关键字取前面的,一个取后面的,不能使两个的索引下标相同。又因为题目保证这样的两个数绝对存在,所以,可以直接让迭代器后移一位,也是相同的关键字。
C++代码实现:
#include
运行结果:
可以看看:http://www.acmerblog.com/leetcode-two-sum-5223.html