Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
**UPDATE (2016/2/13):
**The return format had been changed to zero-based indices. Please read the above updated description carefully.
Solution
遍历数组,使用HashMap保存<value, indice>,一次遍历
- 当target – value在HashMap中时,返回value和target – value的下标
- 当target – value不在HashMap中时,将value和下标插入map中,遍历下一个值
Code
class Solution
{
public:
std::vector<int> twoSum(std::vector<int>& nums, int target)
{
std::map<int, int> hashMap;
std::vector<int> results;
for (std::vector<int>::iterator it = nums.begin();
it != nums.end();
++it)
{
if (hashMap.find(target - *it) != hashMap.end())
{
results.push_back(hashMap[target - *it]);
results.push_back(it - nums.begin());
}
else
{
hashMap.insert(std::make_pair(*it, it - nums.begin()));
}
}
return results;
}
};