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.
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
The naive approach to solving this problem is to loop through each element x
in nums
and then loop through each element again to find if there is a value that equals target
- x
for i = 0 to length of nums
for j = i + 1 to length of nums
if nums[j] == target - nums[i]
return [i, j]
The time complexity can be reduced, by converting the input array into a hash map that stores the value nums[i]
as the key and the index i
as the value. This would involve two iterations, one to build the hash map and another to check if the complement - target - nums[i]
- exists in the hash map but is not the same index.
map = new HashMap
for i = 0 to length of nums
map[nums[i]] = i
for i = 0 to length of nums
complement = target - nums[i]
if map.contains(complement) and map[complement] != i
return [i, map[complement]]
#leetcode #data-structures #rust #algorithms