题目原文
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<int> twoSum(vector<int> &numbers, int target) {
int max = INT_MIN;
int min = INT_MAX;
for (int i=0;i<numbers.size();i++)
{
if(numbers[i] >= max)
max = numbers[i];
if(numbers[i] <= min)
min = numbers[i];
}
vector<short> hashTable(max - min + 1,0);
for (int i=0;i<numbers.size();i++)
{
hashTable[numbers[i]-min] += 1;
}
for (int i=0;i<numbers.size();i++)
{
int leftTarget = target - numbers[i];
if(leftTarget<=max && leftTarget>=min)
{
if ((hashTable[leftTarget-min]>0 && leftTarget != numbers[i])||
(leftTarget == numbers[i] && hashTable[leftTarget-min] > 1))
{
vector<int> out;
out.push_back(i+1);
for (int j=0;j<numbers.size();j++)
{
if(i != j && numbers[j] == target - numbers[i])
{
out.push_back(j+1);
}
}
if(out[0] > out[1])
{
swap(out[0],out[1]);
}
return out;
}
}
}
vector<int> out;
return out;
}