Leetcode 1. 两数之和
1. 两数之和 - 力扣(LeetCode) (leetcode-cn.com)

思路:
1.使用map存储已经遍历过的元素和索引。
2.每遍历一个元素就在map中查找是否有符合要求的元素。
3.只要找到符合要求的元素就直接返回当前元素的索引和符合要求的元素索引。
func twoSum(nums []int, target int) []int {
numMap:=make(map[int]int)
for i,num:=range nums{
targetNum:=target-num
if targetIndex,ok:=numMap[targetNum]; ok{
return []int{i,targetIndex}
}else{
numMap[num]=i
}
}
return []int{}
}

浙公网安备 33010602011771号