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, and you may not use the same element twice.

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums, int target) {
 4        unordered_map<int,int>  Mymap;
 5         vector<int> result;
 6        for(int i=0;i<nums.size();i++){
 7            Mymap[nums[i]]=i;
 8        }
 9        for(int i=0;i<nums.size();i++)
10        {
11            auto iter=Mymap.find(target-nums[i]);
12            if(iter!=Mymap.end()&&i!=iter->second){
13                 result.push_back(i);
14                 result.push_back(iter->second);
15                break;
16            } 
17        }
18         return result;
19     }
20 };

 

posted on 2017-10-03 19:28  wsw_seu  阅读(151)  评论(0编辑  收藏  举报

导航