问题描述
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].
分析
基本思路就是,将target与给定数组中的元素nums[i]做差,得到差值target-nums[i],则然后在数组中寻找此差值 ,按照题意,一定存在以为的两个不同的数,将其相加可以得到target.
在实际实现时,需要注意,如果target是nums中的某元素nums[i]的二倍,则二者相减会得到 nums[i],但是题目要求不能使用相同的元素两次,所以如果找到这样的元素不能返回结果,而是要继续向下找。
代码
class Solution
{
public:
vector<int> twoSum(vector<int>& nums, int target)
{
// 使用hash字典可以大大提高查找速度
unordered_map<int, int> hash;
vector<int> result(2, 0);
for (int i = 0; i < nums.size(); i++)
{
// 在数组中寻找与target的差值
if (hash.find( target - nums[i] ) != hash.end() )
{
// 如果找到了,则返回num[i]和另一个数的索引值
result[0] = hash[ target - nums[i] ] - 1, result[1] = i;
return result;
}
/*
i = 0时,上面的if并不执行,将nums[0]的值和索引1存入map中
i > 1时,如果在hash[0:i-1]中都没有找到,则当前nums[i]
并不能找到一个值nums[j]与其相加等于target。要继续查找下一个元素,
再继续将其与之前的所有元素,重复做差查找操作,直到找到。
*/
hash[nums[i]] = i + 1;
}
}
};