一、问题描述
给出一个全是整数的数组,以及一个数,若数组中两数之和等于这个给定数,返回这两个数在数组中的下标。假设这个数组中总有至少一个结果组合。
比如:
给出 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以 return [0, 1]
二、思路
用一个unordered_map来存这个数组,一个vector来存放结果,用给定数来减去遍历得到的数,如果得到的这个结果能在unordered_map里找到就设置结果vector并返回。
三、code
vector<int> twoSum(vector<int>& nums, int target)
{
unordered_map<int, int> hash;
vector<int> res(2, 0);
for (int i = 0; i < nums.size(); i++)
{
if (hash.find(target - nums[i]) != hash.end())
{
res[0] = hash[target - nums[i]], res[1] = i + 1;
return res;
}
hash[nums[i]] = i + 1;
}
}