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.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
1 class Solution { 2 public: 3 vector<int> twoSum(vector<int>& nums, int target) { 4 vector<int> tm; 5 int a = 0, b = 0; 6 int len = nums.size(); 7 8 multimap<int,int> hash; 9 10 for(int i = 0; i < len; i++){ 11 hash.insert(pair<int,int>(nums[i],i)); 12 } 13 for(int i = 0; i < len; i++){ 14 multimap<int,int>::iterator s; 15 s=hash.find(target-nums[i]); 16 if(s== hash.end()){ 17 continue; 18 } 19 if(i != (*s).second){ 20 a = i; 21 b = (*s).second; 22 break; 23 } 24 } 25 tm.push_back(a); 26 tm.push_back(b); 27 return tm; 28 } 29 };