package leetcode
//hash算法,visited采用hashmap存储,每遍历一个数,就检查target-num的差是否在hashmap存在了,存在则返回,不存在则记录,继续遍历
func twoSum(nums []int, target int) []int { var visited = make(map[int]int,len(nums)) for i, num := range nums{ sub := target - num if j,ok := visited[sub]; ok{ return []int{i,j} }else { visited[num] = i } } return nil }
//穷搜,固定一个数num,搜索剩余数+num?=target
func twoSum2(nums []int, target int) []int { for i, num := range nums{ for j:= i+1; j<len(nums); j++ { if num + nums[j] == target{ return []int{i,j} } } } return nil }
下一篇
区块链实习问题总结
区块链实习问题总结
版权声明:《 leetcode-两数之和-go 》为admin原创文章,转载请注明出处!
最后编辑:2021-2-2 21:02:34