1.题目

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

1.1 示例
	给定 nums = [2, 7, 11, 15], target = 9
	因为 nums[0] + nums[1] = 2 + 7 = 9
	所以返回 [0, 1]
2.思路
2.1 把数组nums中的整数通过for循环放到字典中
2.2 通过目标值和数组,在字典中进行查找
2.3 判断空、重复的情况
3.题解
def twoSum(nums, target):
        hashmap = {}
        # 2.1 把数组nums中的整数通过for循环放到字典中
        for idx, num in enumerate(nums):
            hashmap[num] = idx
        # 2.2 通过目标值和数组,在字典中进行查找
        for i,num in enumerate(nums):
            j = hashmap.get(target - num)
            # 2.3 判断空、重复的情况。
            if j is not None and j != i:
                return [i,j]
                
# 测试
print(twoSum([2, 7, 11, 15], 9))
4.耗时
运行时间:60 ms
内存消耗:15.6 MB

本文地址:https://blog.csdn.net/qq_41293896/article/details/107144431