0x00
难度:Easy
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].
0x01
本题很简单,最暴力的方法是循环遍历数组:
func twoSum(nums []int, target int) []int {
var ret []int
for i,vi := range nums {
for j,vj := range nums[i+1:] {
if vi + vj == target {
return append(ret,i,i + j + 1)
}
}
}
return ret
}
但是我们仔细审题会发现
have exactly one solution, and you may not use the same element twice.
这就意味着如果vi + vj = target,那么只要知道 vj 的值,vi 的值就等于target - vi,而且 vi 与 vj 是唯一的,因此可以将vi,vi作为key,使用map更高效的实现。
func twoSum(nums []int, target int) []int {
var ret []int
m := make(map[int]int)
for i,vi := range nums {
if j,ok := m[target - vi];ok {
return append(ret,j,i)
}
m[vi] = i
}
return ret
}