To solve this problem in Javascript, we can use the hashing technique to store the indices of the numbers as we traverse through the array. We can use a hashmap to store the target difference and the index of its complement. If we find a number whose complement is already present in the hashmap, then we can return its indices.
Here's the implementation:
index.tsx340 chars19 lines
In the above code snippet, we have defined a function twoSum
that takes an array nums
and an integer target
as arguments. We have also defined a hashmap hash
to store the indices of the numbers.
We then iterate through the array nums
using a for
loop and find the complement of the current number with respect to the target
. If the complement is already present in the hashmap, we return its indices with the current index. Otherwise, we add the current number and its index to the hashmap.
At the end of the function, we call console.log
with the function call twoSum(nums, target)
to print the output. The output in this case is [0, 1], which means that the numbers at indices 0 and 1 add up to the target value of 9 in the input array.
gistlibby LogSnag