Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
需要注意的地方,给定的vector中数值无序、正负数、0值、相同数值
-
vector<int> twoSum(vector<int> &numbers, int target) {
-
vector<int> result;
-
map<int, vector<int> > imap;
-
int pos1 = 0;
-
int pos2 = 0;
-
for(unsigned int i = 0; i < numbers.size(); i++)
-
{
-
map<int, vector<int> >::iterator it = imap.find(numbers[i]);
-
if(it != imap.end())
-
{
-
it->second.push_back(i);
-
//cout << "key: " << it->first << " value: " << it->second.size() << endl;
-
}
-
else
-
{
-
vector<int> ivec;
-
ivec.push_back(i);
-
imap.insert(make_pair<int, vector<int> >(numbers[i],ivec));
-
}
-
}
-
for(unsigned int i = 0; i < numbers.size(); i++)
-
{
-
int temp = target - numbers[i];
-
map<int, vector<int> >::iterator it = imap.find(temp);
-
if(it != imap.end())
-
{
-
if(temp == numbers[i] && it->second.size() >= 2)
-
{
-
for(unsigned int j = 0; j < it->second.size(); j++)
-
{
-
result.push_back(it->second[j] + 1);
-
}
-
return result;
-
}
-
else if(it->first != numbers[i])
-
{
-
pos1 = i + 1;
-
pos2 = it->second[0] + 1;
-
result.push_back(pos1);
-
result.push_back(pos2);
-
return result;
-
}
-
}
-
}
-
return result;
-
}
阅读(4408) | 评论(0) | 转发(0) |