1. 题目描述
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
2. 解题思路
选取数组 nums
中的第一个数 num
,用 target
减去,得到 another_num
,即 num +another_num = target
,在剩余的数中寻找 another_num
,如果存在,返回两个数的索引。依次遍历整个数组。
基本思路是这样,但在 “在剩余的数中寻找num2” 这一步,寻找算法的好坏直接影响整体算法的效率。
因为数组中同一个元素不能使用两遍,这就在于 “在剩余的数中寻找num2” 中的 “剩余” 怎么实现了,不能简单地使用 if another_num in nums
,需要将寻找的 num
从查找数组 nums
中剔除,这样查找数组才是剩余的。
3. 代码
3.1暴力查找
外循环确定 num
,内循环查找 another_num
,由于内循环从 i+1
开始,保证了查找数组中不包含 num
。
但暴力查找效率极低。
def twoSum0(nums, target):
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i] + nums[j] == target:
return [i,j]
3.2 哈希表查找
保持数组中的每个元素与其索引相互对应的最好方法是什么?哈希表。
用字典模拟哈希表。
使用 enumerate()
函数获取 nums
列表元素和对应索引,并将 another_num
及其对应的索引存入字典,在原列表 nums
里遍历 num
,在字典里寻找对应 another_num
。
def twoSum1(nums, target):
hashmap = {}
for index, num in enumerate(nums):
another_num = target - num
if another_num in hashmap:
return [hashmap[another_num], index]
else:
hashmap[num] = index
return None