题目描述:
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
知识点:
哈希->散列函数
Hash算法,是将一个不定长的输入,通过散列函数变换成一个定长的输出,即散列值。
使用Hash算法的数据结构叫做哈希表,也叫散列表,主要是为了提高查询的效率。它通过把关键码值映射到表中一个位置来访问记录,以加快查找的速度。
思路和代码:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hash_dict = dict() # 使用字典作为查找对象,字典的in 时间复杂度位O(1),列表的in 时间复杂度位O(n)
for index, value in enumerate(nums):
# enumerate()将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列
sub = target - value
if sub in hash_dict:
return [hash_dict[sub], index]
# 字典按值获取索引
else:
hash_dict[value] = index
# 插入字典