1. Description of the topic
2. Topic analysis
Consider using the hashMap method to store each element in the array corresponding to the following table, then traverse the array, calculate the difference between the target and each element in the array, and search in the hashMap until the last pair is found.
3. Code
1 vector<int> twoSum(vector<int>& nums, int target) { 2 vector<int> ans; 3 unordered_multimap<int,int> m; 4 for( size_t i = 0; i< nums.size() ; i++) 5 m.insert(make_pair(nums[i],i)); 6 7 for(size_t i = 0; i < nums.size() ; i++) 8 { 9 auto ite = m.find( target - nums[i] ); 10 if( ite != m.end() && i < ite->second ) 11 { 12 ans.push_back(i); 13 ans.push_back(ite->second); 14 } 15 } 16 return ans; 17 18 }