//1.map解法 functwoSum(numbers []int, target int) []int { maps := make(map[int]int) for i, num := range numbers { if j, ok := maps[target-num]; ok { return []int{j, i} } maps[num] = i } return []int{} }
// 2. 二分查找 functwoSum(numbers []int, target int) []int { iflen(numbers) == 0 { return []int{} } for i := 0; i < len(numbers); i++ { t := target - numbers[i] index := binarySearch(numbers, t, i+1, len(numbers)-1) if index != -1 { return []int{i, index} } } return []int{} }
funcbinarySearch(numbers []int, t, left, right int)int { for left <= right { mid := (left + right) >> 1 if numbers[mid] == t { return mid } elseif numbers[mid] > t { right = mid - 1 } elseif numbers[mid] < t { left = mid + 1 } } return-1 }
for left < right { sum := numbers[left] + numbers[right] if sum == target { return []int{left, right} } elseif sum < target { left++ } else { right-- } }