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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
从数组中找出两个数相加和为 target,每个数不能重复使用。数组中只可能存在一对数满足要求。要求给出满足要求的两个数的下标。
用 map 就可以简单解决问题。
func twoSum(nums []int, target int) []int {
res := []int{}
mm := make(map[int]int)
for i, v := range nums{
index, ok := mm[target - v]
if ok {
res = []int{index, i}
return res
}
mm[v] = i
}
return res
}