
暴力解法:
python
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)-1):
for j in range(i+1,len(nums)):
if (nums[i]+nums[j]) == target:
return [i,j]

空间换时间:哈希表
python
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# 创建一个空字典,用来做"空间换时间"
# 格式为 {数字: 这个数字对应的索引}
hash_map = {}
for i in range(len(nums)):
current_num = nums[i]
complement = target-nums[i]
if complement in hash_map:
return [hash_map[complement],i]
hash_map[current_num] = i
