问题是:找到两个数字的索引nums[index1] + nums[index2] == target。这是我的尝试golang(索引从 1 开始):
package main
import (
"fmt"
)
var nums = []int{0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 25182, 25184, 25186, 25188, 25190, 25192, 25194, 25196} // The number list is too long, I put the whole numbers in a gist: https://gist.github.com/nickleeh/8eedb39e008da8b47864
var target int = 16021
func twoSum(nums []int, target int) (int, int) {
if len(nums) <= 1 {
return 0, 0
}
hdict := make(map[int]int)
for i := 1; i < len(nums); i++ {
if val, ok := hdict[nums[i+1]]; ok {
return val, i + 1
} else {
hdict[target-nums[i+1]] = i + 1
}
}
return 0, 0
}
func main() {
fmt.Println(twoSum(nums, target))
}
nums 列表太长,我把它放在一个gist中:https : //gist.github.com/nickleeh/8eedb39e008da8b47864
这段代码工作正常,但我发现这return 0,0部分很难看,而且运行速度比Julia翻译慢十倍。我想知道是否有任何部分写得很糟糕并影响性能?
编辑: 朱莉娅的翻译:
function two_sum(nums, target)
if length(nums) <= 1
return false
end
hdict = Dict()
for i in 1:length(nums)
if haskey(hdict, nums[i])
return [hdict[nums[i]], i]
else
hdict[target - nums[i]] = i
end
end
end
绝地无双
呼如林
相关分类