# leetcode--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:

1 Given nums = [2, 7, 11, 15], target = 9,
2 Because nums[0] + nums[1] = 2 + 7 = 9,
3 return [0, 1].

 1 vector<int> addToTarget(vector<int> &num,int target)
2 {
3   vector<int> res;
4   for(auto it1 = num.begin(); it1 != num.end();++it1)
5     for(auto it2 = num.begin();it2 != num.end();++it2)
6       {
7         if(*it1 + *it2 == target && it1 != it2)
8           {
9             res.push_back(static_cast<int>(it1 - num.begin()));
10             res.push_back(static_cast<int>(it2 - num.begin()));
11             return res;
12           }
13       }
14 }

 1 vector<int> addToTarget(vector<int> &num,int target)
2 {
3   vector<int> res(2);
4   unordered_map<int,int> hashMap;
5   for(auto it=num.begin();it != num.end(); ++it)
6     {
7       if(hashMap.count(target - *it))
8         {
9           res[0]=hashMap[target-*it];
10           res[1]=static_cast<int>(it-num.begin());
11           return res;
12         }
13       hashMap[*it] = static_cast<int>(it-num.begin());
14     }
15 }

posted @ 2016-06-24 10:17  魄魄熊  阅读(238)  评论(0编辑  收藏  举报