twoSum does not assume that nums is sorted.
(nums []int, target int)
| 2 | |
| 3 | // twoSum does not assume that nums is sorted. |
| 4 | func twoSum(nums []int, target int) []int { |
| 5 | numsLen := len(nums) |
| 6 | if numsLen < 2 { |
| 7 | return []int{} |
| 8 | } |
| 9 | |
| 10 | numToIndex := make(map[int]int) |
| 11 | for idx, num := range nums { |
| 12 | need := target - num |
| 13 | mIdx, ok := numToIndex[need] |
| 14 | if ok { |
| 15 | return []int{mIdx, idx} |
| 16 | } |
| 17 | |
| 18 | numToIndex[num] = idx |
| 19 | } |
| 20 | |
| 21 | return []int{} |
| 22 | } |
| 23 | |
| 24 | // twoSumSortedInput assumes that nums is sorted. |
| 25 | func twoSumSortedInput(nums []int, target int) []int { |