# LeetCode: 1. Two Sum

## 题目¶

Given an array of integers nums and and integer target, return the indices of the two numbers such that they add up to target.

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

You can return the answer in any order.

Example 1:

```Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1]
```

Example 2:

```Input: nums = [3,2,4], target = 6
Output: [1,2]
```

Example 3:

```Input: nums = [3,3], target = 6
Output: [0,1]
```

Constraints:

• 1 <= nums.length <= 10^5
• -109 <= nums[i] <= 10^9
• -109 <= target <= 10^9
• Only one valid answer exists.

## 解法¶

### 暴力多次遍历查找¶

```class Solution(object):
def twoSum(self, nums, target):
length = len(nums)

for current_i, current_value in enumerate(nums):
another_i_start = current_i + 1

for another_i, another_v in enumerate(nums[another_i_start: length], another_i_start):
if current_value + another_v == target:
return [current_i, another_i]
```

### 一次循环查找¶

```class Solution(object):
def twoSum(self, nums, target):
another_value_to_current_index_map = {}

for current_index, current_value in enumerate(nums):
another_value = target - current_value

if current_value in another_value_to_current_index_map:
pre_index = another_value_to_current_index_map[current_value]
return [pre_index, current_index]

another_value_to_current_index_map[another_value] = current_index
```