转职1年开发后,回头看原来写的代码,当初还是留下了一些小的瑕疵,优化空间很大……
原先:
func twoSumOrg(nums []int, target int) []int {
numMap := make(map[int]int)
result := make([]int, 2)
for i, num := range nums {
_, ok := numMap[num]
if ok {
result[0], result[1] = i, numMap[num]
} else {
numMap[target-num] = i
}
}
return result
}
现在:
func twoSum(nums []int, target int) []int {
numMap := make(map[int]int, len(nums))
result := make([]int, 2)
for i, num := range nums {
_, ok := numMap[num]
if ok {
result[0], result[1] = i, numMap[num]
break } else {
numMap[target-num] = i
}
}
return result
}
对比结果:
Benchmark_twoSum-8 20000000 87.5 ns/op
Benchmark_twoSumOrg-8 10000000 137 ns/op
并且,还能进一步优化:
func twoSum(nums []int, target int) []int {
numMap := make(map[int]int)
result := make([]int, 2)
for i, num := range nums {
_, ok := numMap[num]
if ok {
result[0], result[1] = i, numMap[num]
break } else {
numMap[target-num] = i
}
}
return result
}
Benchmark_twoSum-8 20000000 84.0 ns/op
没有评论:
发表评论