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

你可以假设每种输入只会对应一个答案,并且你不能使用两次相同的元素。

你可以按任意顺序返回答案。

示例 1:

输入: nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

示例 2:

输入: nums = [3,2,4], target = 6
输出:[1,2]

示例 3:

输入: nums = [3,3], target = 6
输出:[0,1]

提示:

  • 2 <= nums.length <= 104
  • -109 <= nums[i] <= 109
  • -109 <= target <= 109
  • 只会存在一个有效答案

这个题是经典的 Two Sum(两数之和),最优解法使用哈希表(字典)在一次遍历中解决,时间复杂度为 O(n)

  • 对于每个元素 num,计算出需要的另一个数 complement = target - num
  • 如果 complement 已经在哈希表中,说明找到了答案。
  • 否则,将当前数和索引存入哈希表,继续遍历。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
from typing import List

class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# 创建一个哈希表,用于存储数字和对应的下标
hashmap = {}
for i, num in enumerate(nums):
complement = target - num # 计算目标差值
if complement in hashmap:
# 找到了满足条件的两个数,返回下标
return [hashmap[complement], i]
# 把当前数字加入哈希表
hashmap[num] = i