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
这道题的关键点在于控制算法的时间复杂度,刚开始楼主采用快速排序和二分查找的方法,发现时间复杂度还是通不过(觉得主要是对于那种已经排好序的序列,快排并没有对时间有太大提高)。随后楼主采用了网上大神建议的哈希表的方法总算是一个葫芦画个瓢的解决了,也小小的学习了一下哈希表的用法。
功能测试用例:{0,11,7,15,6,4,20},10;{0,11,7,15,4,6,20},10
特殊输入测试用例:{3,2,4},6;{0,4,6,7,11,15,20},10
class Solution
{
public:
vector<int> twoSum(vector<int> &numbers, int target)
{
vector<int> vnResult;
map<int, int> nnMap;//创建一个哈希表,用来存储数值和位置的关系
int nRest;
for (int nTemp = 0; nTemp < numbers.size(); nTemp++)
{
nRest = target - numbers[nTemp];//计算目标数值减去当前值的剩余
if (nnMap.count(nRest) != 0)//如果剩余值存在于哈希表中则将当前值和剩余值的位置输入到结果向量中
{
vnResult.push_back(nnMap[nRest]);
vnResult.push_back(nTemp + 1);
return vnResult;
}
if (nnMap.count(numbers[nTemp]) == 0)//如果哈希表没有当前值则将当前值插入哈希表
{
nnMap.insert(pair<int, int>(numbers[nTemp], nTemp + 1));
}
}
return vnResult;
}
};