2020-8-15 Daily reading notes-the sum of two numbers
Use unordered_map to construct a mapping, and directly store target-nums[i] (that is, the complement corresponding to the current element). When traversing nums[i], see if nums[i] exists in the hash table.
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target)
{
unordered_map<int, int> hm;
for(int i = nums.size() - 1; i >= 0; --i)
{
auto iter = hm.find(nums[i]);
if(iter != hm.end())
return {
i, iter->second};
int diff = target - nums[i];
hm[diff] = i;
}
return {
};
}
};