## 原題

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

## 分析

• 目標：兩元素的索引
• 依據：兩元素的值之和與給定的值是否相等

## 實現

### 雙重循環

`````` 1func twoSum(nums []int, target int) []int {
2    for i := 0; i < len(nums); i++ {
3        for j := i + 1; j < len(nums); j++ {
4            if nums[i]+nums[j] == target {
5                return []int{i, j}
6            }
7        }
8    }
9
10    return []int{}
11}
``````

### Map

`````` 1func twoSum(nums []int, target int) []int {
2    m := map[int]int{}
3    for i := 0; i < len(nums); i++ {
4        m[nums[i]] = i
5    }
6
7    for i := 0; i < len(nums); i++ {
8        minus := target - nums[i]
9        if j, ok := m[minus]; ok && i != j {
10            return []int{i, j}
11        }
12    }
13
14    return []int{}
15}
``````

### Map 改良版

`````` 1func twoSum(nums []int, target int) []int {
2    m := map[int]int{}
3
4    for i := 0; i < len(nums); i++ {
5        minus := target - nums[i]
6        if j, ok := m[minus]; ok {
7            return []int{i, j}
8        }
9
10        // the code placed here can avoid using the same element twice.
11        m[nums[i]] = i
12    }
13
14    return []int{}
15}
``````