[Leetcode] 001 Two Sum

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;
    }
};
    原文作者:周肃
    原文地址: https://www.jianshu.com/p/a4e1e23e23d4
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞