题目
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].
给出任意一个整型数组,从数组中选取两个不同元素相加等于一个指定值,要求返回这两个数组元素的索引。
思路
解法1
package main
import "fmt"
func twoSum(nums []int, target int) []int {
a := make(map[int]int, len(nums))
for i, e := range nums {
if j, ok := a[target-e]; ok {
return []int{j, i}
}
a[e] = i
}
return nil
}
func main() {
fmt.Println(twoSum([]int{2, 7, 11, 15}, 9))
}