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.
Subscribe to see which companies asked this question
1 #include<iostream> 2 #include<map> 3 #include<vector> 4 using namespace std; 5 class Solution { 6 public: 7 vector<int> twoSum(vector<int>& nums, int target) { 8 vector<int> res; 9 map<int,int> hashmap; 10 int find_num; 11 for(int i=0;i<nums.size();i++) 12 { 13 find_num=target-nums[i]; 14 map<int,int>::iterator it=hashmap.find(find_num); 15 if(it!=hashmap.end()) 16 { 17 res.push_back(i); 18 res.push_back(it->second); 19 return res; 20 } 21 hashmap[nums[i]]=i; 22 } 23 } 24 };