解决方法:
- 直接两次循环,两数相加为target则return,时间复杂度 O( n 2 n^2 n2)
func twoSum(nums []int, target int) []int {
for ai, a:=range nums{
for bi, b:=range nums[ai+1:]{
if a+b == target{
return []int{ai, bi+ai+1}
}
}
}
return []int{}
}
- 使用map,将所有的数存入map中,value -> index
使用go语言编码
func twoSum(nums []int, target int) []int {
res := map[int]int{}
for ai, a:=range nums{
if bi, ok := res[target - a]; ok{
return []int{bi, ai}
}
res[a] = ai
}
return []int{}
}