题目
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].
解题思路
方案一
两层循环,遍历所有可能性,找到目标解
func twoSum(nums []int, target int) (ret []int) {
numLen := len(nums)
for i := 0; i < numLen-1; i++ {
// fmt.Printf("%d: %d\n", i, nums[i])
for j := i + 1; j < numLen; j++ {
sum := nums[i] + nums[j]
// fmt.Printf("sum:%d = %d + %d\n", sum, nums[i], nums[j])
if target == sum {
ret = []int{i, j}
}
}
}
return ret
}
方案二
将数组中的值val和位置pos对应的键值对放入map中,通过hash表查找使val2 = target - val 的值,如果找到则返回结果,找不到,则将当前值插入map
注意
如果先把所有值都放入map中,如果目标结果是两个相同值相加得到的,则不能找到目标结果,比如
nums = []int{3,3}, target = 6
func twoSum(nums []int, target int) []int {
var numMap map[int]int
numMap = make(map[int]int)
var ret []int
for index, val := range nums {
val2 := target - val
fmt.Printf("val:%+v, index:%+v, val2:%+v\n", val, index, val2)
index2, ok := numMap[val2]
if ok && index != index2 {
ret = []int{index, index2}
break
}
numMap[val] = index
}
fmt.Printf("numMap:%+v\n", numMap)
return ret
}
测试
twoSum_test.go
package _1_Two_Sum
import "testing"
func TestTwoSum(t *testing.T) {
var tests = []struct{
input []int
target int
output []int
}{
{[]int{3, 2, 4}, 6, []int{1, 2}},
{[]int{3, 3}, 6, []int{0, 1}},
}
for _, v := range tests {
ret := TwoSum(v.input, v.target)
if ret[0] == v.output[0] && ret[1] == v.output[1] {
t.Logf("pass")
} else if ret[0] == v.output[1] && ret[1] == v.output[0] {
t.Logf("pass")
} else {
t.Errorf("fail, want %+v, get %+v", v.output, ret)
}
}
}