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.
- The idea is to create a hashmap (
value -> index
). We can just start with an empty map instead of creating a whole map of the array. - For a given number
n
in the array, we calculate its difference from the target. - If this difference is in our map, we can return the index of the difference and our current number.
- If it’s not, we will add
n
and its indexi
to the hashmap as the key and value respectively.
Uglier hashmap solution that initializes: