遍历一遍,将数字存到 map,每次遍历求 right,看是否在 map 中
package main
import "fmt"
func main() {
nums := []int{2, 7, 11, 15}
target := 9
fmt.Println(twoSum(nums, target))
}
func twoSum(nums []int, target int) []int {
numMap := make(map[int]int)
for i, left := range nums {
right := target - left
index, ok := numMap[right]
if ok && index != i {
return []int{index, i}
}
numMap[left] = i
}
return []int{-1, -1}
}