以下是解决两数之和问题的两种方法:
方法一:暴力枚举
思路:遍历数组中的每个元素,并将其与其他所有元素进行比较,如果两个元素的和等于目标值,则返回这两个元素的下标。
代码:
Python
def two_sum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
return []
Use code with caution.
方法二:哈希表
思路:使用哈希表存储数组中的元素及其下标,遍历数组中的每个元素,并检查目标值减去当前元素是否在哈希表中,如果存在,则返回当前元素的下标和哈希表中对应元素的下标。
代码:
Python
def two_sum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hash_table = {}
for i, num in enumerate(nums):
complement = target - num
if complement in hash_table:
return [i, hash_table[complement]]
hash_table[num] = i
return []
Use