Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
func twoSum(nums []int, target int) []int {
result := make([]int, 2)
numIndex := make(map[int]int) // number -> index mapping
for i, n := range nums {
want := target - n
wantIndex, contains := numIndex[want]
if contains {
result[0] = wantIndex
result[1] = i
break
}
numIndex[n] = i
}
return result
}