functwoSum(nums []int, target int) []int { var ret []int for index1, num1 := range nums { for index2, num2 := range nums { if index1 != index2 && num1+num2 == target { ret = []int{index2, index1} return ret } } } return ret }
时间复杂度: O(n^2)
空间复杂度: O(1)
一遍哈希表
functwoSum(nums []int, target int) []int { var ( ret []int numsMap map[int][]int ) numsMap = make(map[int][]int, len(nums)) for index, num := range nums { if _, ok := numsMap[num]; ok { numsMap[num] = append(numsMap[num], index) } else { numsMap[num] = []int{index} } if indexList, ok := numsMap[target-num]; ok { for _, i := range indexList { if i != index { ret = []int{i, index} return ret } } } } return ret }