leetcode [001] : Two Sum

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

 

思路:
1、使用给定数字target减去数组nums[i]得到一个数字iSub
2、查询数字iSub是不是在数组nums里面
3、为了使查询速度加快,需要提前添加一个哈希表
4、哈希表需要考虑会有重复数字出现的情况,例如数组里面有两个7
5、哈希表需要考虑iSub和nums[i]相等的情况,例如target等于6,nums[i]等于3,则iSub也等于3(这种情况,哈希就会查到自己身上去)
6、为此,我定义的哈希为<int, vector<int>>类型,也就是出现相同数字的时候,访问哈希下的vector<int>,往里面push我们的index即可
7、nums[i]和iSub相等的时候,必须是哈希里面vector的size()大于等于2

源代码如下:

#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
using namespace std;

class Solution {
public:

    void buildHash(vector<int>& nums)
    {
        int iLen = nums.size();
        for (int i = 0; i < iLen; ++i)
        {
            hashDict[nums[i]].push_back(i + 1);
        }
    }

    vector<int> twoSum(vector<int>& nums, int target)
    {
        vector<int> vecResult;
        buildHash(nums);

        int iNumSub = 0;
        unordered_map<int, vector<int>>::iterator it;
        for (int i = 0; i < nums.size(); ++i)
        {
            iNumSub = target - nums[i];
            it = hashDict.find(iNumSub);
            if (it != hashDict.end())
            {
                if (iNumSub == nums[i])
                {
                    if (hashDict[iNumSub].size() >= 2)
                    {
                        vecResult.push_back(hashDict[iNumSub][0]);
                        vecResult.push_back(hashDict[iNumSub][1]);
                    }
                    else
                    {
                        continue;
                    }
                }
                else if (hashDict[iNumSub][0] >= i + 1)
                {
                    vecResult.push_back(i + 1);
                    vecResult.push_back(hashDict[iNumSub][0]);
                }
                else
                {
                    vecResult.push_back(hashDict[iNumSub][0]);
                    vecResult.push_back(i + 1);
                }
                return vecResult;
            }
        }
        return vecResult;
    }

private:
    unordered_map<int, vector<int>> hashDict;
};

int main()
{
    vector<int> vecA;
    vector<int> vecResult;
    vecA.push_back(3);
    vecA.push_back(2);
    vecA.push_back(4);

    Solution a;
    vecResult = a.twoSum(vecA, 6);

    printf("%d %d\n", vecResult[0], vecResult[1]);

    system("pause");
    return 0;
}

 

posted @ 2015-09-10 20:17  lqy1990cb  阅读(116)  评论(0)    收藏  举报