# 两数之和

``````

``````

## 解决方案

### 暴力法

#### Python 实现方式

``````
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
nums_len = len(nums)
for i in range(nums_len):
for j in range(i+1, nums_len):
if nums[i] + nums[j] == target:
# l = []
# l.append(i)
# l.append(j)
return [i, j]

``````

#### JavaScript 实现方式

``````
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
len = nums.length;
for(let i = 0; i < len; i++) {

for(let j = i + 1; j < len; j++){
if (nums[i] + nums[j] === target) {
return [i, j];
}
}
}
return l;
};

// let nums = [2, 7, 11, 15, 3, 6, 4, 5];

// let result = twoSum(nums, 9)

// console.log(result)
``````

### 利用哈希表

#### Python

Python 中的字典数据类型就是 Hash 表实现的。

``````    def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# 创建字典，列表值为key，索引为 value
nums_dict = { nums[i]: i for i in range(len(nums)) }
for i in range(len(nums)):
# 更具目标值，求出剩余值
complement = target - nums[i]
# 查看字典是否有符合的
if nums_dict.get(complement) and nums_dict.get(complement) != i:
return [i, nums_dict.get(complement)]
``````

#### JavaScript

``````
var twoSum = function(nums, target) {
let num_json = {}
nums.forEach((item, index) => {
num_json[item] = index
})

for (let i in nums) {
let complement = target - nums[i]

if (num_json[complement] && num_json[complement] != i) {
return [i - 0, num_json[complement] ]
}
}
};

let nums = [2, 7, 11, 15, 3, 6, 4, 5];
let result = twoSum(nums, 9)
console.log(result)

``````
image.png

### 一遍哈希表

``````    def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
nums_dict = {}

# 创建字典，列表值为key，索引为 value
for i in range(len(nums)):
# 根据目标值，求出剩余值
complement = target - nums[i]

if complement in nums_dict:
return [i, nums_dict.get(complement)]

nums_dict[nums[i]] = i
``````
image.png