普通写法
func twoSum2(nums []int, target int) []int {
for key, val := range nums {
for k, v := range nums[(key + 1):] {
if val+v == target {
nums[0] = key
nums[1] = k + key + 1
return nums[0:2]
}
}
}
return nil
}
速度为36ms
优化写法,用go的map实现,用哈希表会快很多
func twoSum(nums []int, target int) []int {
//创建一个map
maps := make(map[int]int, len(nums)/2)
for k, value := range nums {
if num1, ok := maps[target-value]; ok {
return []int{k, num1}
}
maps[value] = k
}
return []int{0, 0}
}
网友评论