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.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.//原先索引从1开始,现在改成从0开始.
哈希表,先取出一个数,然后用target减去这个数得到gap,查找gap是否存在于之后的数组里.
最后返回一个vector<int>类型的索引.
vector<int> TwoSum(vector<int>&nums, int target)
{
unordered_map<int, int >hashTable;
vector<int>result;
for (int i = 0; i < nums.size(); i++)
hashTable[nums[i]] = i;//赋上坐标值
for (int i = 0; i < nums.size(); i++) //i为取出值的坐标
{
const int gap = target - nums[i];
if (hashTable.find(gap) != hashTable.end() && hashTable[gap]>i)//规定index0小于index1
{
result.push_back(i);
result.push_back(hashTable[gap]);
break;
}
}
return result;
}
本文介绍了一种解决两数之和问题的有效算法。通过使用哈希表预先存储数组元素及其索引,可以快速找到目标和对应的两个数的索引。此算法确保每个输入恰好有一个解决方案,并以零为基础的索引形式返回结果。

400

被折叠的 条评论
为什么被折叠?



