给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

解法一:哈希表法

  1. class Solution:
  2. def twoSum(self, nums: List[int], target: int) -> List[int]:
  3. maps = {}
  4. for i, n in enumerate(nums):
  5. if target - n in maps:
  6. return maps[target - n], i
  7. maps[n] = i

解法二:暴力法

  1. class Solution:
  2. def twoSum(self, nums: List[int], target: int) -> List[int]:
  3. n = len(nums)
  4. for i in range(n):
  5. for j in range(i + 1, n):
  6. if nums[i] + nums[j] == target:
  7. return [i, j]
  8. return []

解法三:双指针法

需要先排序,然后数组起始结束各一个指针向中间移动寻找target

  1. class Solution:
  2. def twoSum(self, nums: List[int], target: int) -> List[int]:
  3. start, end = 0, len(nums) - 1
  4. while start < end:
  5. s = nums[start] + nums[end]
  6. if s == target:
  7. return start, end
  8. elif s > target:
  9. end -= 1
  10. else:
  11. start += 1
  12. return -1, -1