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
这里需要注意返回的是索引,所以需要记录一下。如果有两个元素的值一样大,那么还需要注意使用哈希表存储的时候要把第一次查询到的删掉。
例如:5 2 3 2 ,target = 4时,那么返回的索引应该是 2 4
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> result;
unordered_multimap<int,int> nimap;
for (int i = 0; i < numbers.size(); i++)
nimap.insert(make_pair(numbers[i], i+1));
sort(numbers.begin(), numbers.end());
size_t i = 0, j = numbers.size() - 1;
while(i < j)
{
int a = numbers[i], b = numbers[j];
if (a + b == target)
{
auto ite1 = nimap.find(a);
nimap.erase(ite1);
auto ite2 = nimap.find(b);
result.push_back(ite1->second);
result.push_back(ite2->second);
if (result[0] > result[1])
swap(result[0], result[1]);
return result;
}
else if (a + b < target)
++i;
else
--j;
}
return result;
}
};