// 方法一:暴力枚举,两次循环 functwoSum(nums []int, target int) []int { for i := 0; i < len(nums); i++ { for j := i+1; j < len(nums); j++ { if nums[i]+nums[j] == target { return []int{i, j} } } } returnnil }
// 方法二:通过中间 Map 记录遍历过的数字及其对应的索引 functwoSum(nums []int, target int) []int { m := map[int]int{} for i, v := range nums { if k, ok := m[target-v]; ok { return []int{k, i} } m[v] = i } returnnil }