题目描述:
给定一个整数数组nums和一个目标值target,请在该数组中找出和为目标值的那两个整数,并返回它们的数组下标。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
解题思路:借用Python字典,遍历元素的时候,记录元素的下标,当找到target-a的时候,只需再查找字典即可,查找字典时间复杂度为O(1)。所以,时间复杂度为O(n),空间复杂度为O(n)。
有两个值得注意的地方:
- 同样的元素不能重复使用(也就是不能自己加自己)
- 给定的数组中可能有相同的元素(比如 [3, 3, 4, 4, 5])
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
n = len(nums)
lookup = {}
for i in range(n):
tmp = target - nums[i]
if tmp in lookup:
return [lookup[tmp], i]
lookup[nums[i]] = i