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].
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int res1 = 0, res2 = 0;
multimap<int,int> m;
multimap<int,int>::iterator it;
multimap<int,int>::iterator it2;
vector<int> res;
for(int i=0;i<nums.size();i++)
{
m.insert(make_pair(nums[i],i));
}
it2 = m.begin();
for(int i=0;i<nums.size();i++)
{
if(it2->first > target/2)
break;
it = m.find(target-it2->first);
if(it!=m.end() && it!=it2)
{
res1 = it->second;
res2 = it2->second;
break;
}
it2++;
}
if(res1 > res2)
swap(res1,res2);
res.push_back(res1);
res.push_back(res2);
return res;
}
};