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;
}
};

本文介绍了一种解决两数之和问题的高效算法。给定一个整数数组及目标值,找出数组中和为目标值的两个数的索引。算法使用了有序映射来辅助查找,确保每个元素只被使用一次。
348

被折叠的 条评论
为什么被折叠?



