题目
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回它们的数组下标。你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素作为加数。
- 示例
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
解题思路
解法一:
获取数组长度n,2个for循环判断之和是否为target
代码
def twoSum(self, nums: List[int], target: int) -> List[int]:
n=len(nums)
for i in range(n):
for j in range(i+1,n):
if target-nums[i]==nums[j]:
return [i,j]
解题思路
用字典(哈希表)存储每个数对应的索引
当target - 当前数 在 字典(哈希表) 中存在时,说明已存储的数和当前数相加可以达到目标target
返回对应的索引 [hashmap[target - num], i]
代码
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashmap = {}
for i, num in enumerate(nums):
if target - num in hashmap:
return [hashmap[target - num], i]
hashmap[num] = i
- enumerate()是用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标。i 是下标,num是值;