leetcode-两数之和-go

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
}
发表评论 / Comment

用心评论~