Two Sum
Problem statement
Pick two different indices in numbers whose values add up to targetSum, and return those indices. Prefer a single-pass approach when you can.
Example:
Input:
numbers = [2, 7, 11, 15], targetSum = 9
Expected output:
[0, 1]
Why: 2 + 7 = 9.
Practice on LeetCode: Two Sum
Golang Solution
func twoSum(numbers []int, targetSum int) []int {
tempMap := map[int]int{}
for index, val := range numbers {
if res, ok := tempMap[targetSum-val]; ok {
return []int{index, res}
} else {
tempMap[val] = index
}
}
return []int{-1, -1}
}
