Two Sum
Problem
Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Follow-up: Can you come up with an algorithm that is less than O(n2)
time complexity?
Constraints
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
- Only one valid answer exists.
Solution
The problem Two Sum
can be solved by inserting each integers into a hash table and checking for the corresponding value in the table.
Implementation
typedef unordered_map<int, int> Map;
class Solution
{
public:
vector<int> twoSum(vector<int> &nums, int target)
{
Map nums_map;
vector<int> ret;
for (int i = 0; i < nums.size(); i++)
{
Map::iterator it = nums_map.find(target - nums[i]);
if (it != nums_map.end())
{
ret = {it->second, i};
break;
}
nums_map[nums[i]] = i;
}
return ret;
}
};