题目
给定一个无重复的整数数组和一个目标值,找出数组中两个和为目标值的元素的索引。
举例
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
解法
最简单的做法是使用双重循环。
def twoSum(nums, target):
for i in range(0, len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
但是时间复杂度为 O(n^2),空间复杂度为 O(1),无法通过。
改用HashTable保存列表数据,以空间换取时间
def twoSum(nums, target):
dct = {}
for i, x in enumerate(nums):
dct[x] = i
for i, x in enumerate(nums):
j = dct[target - x] if target - x in dct else -1 #关键之处
if j != -1 and j != i:
return [i, j]
再进一步,在单次循环中处理
def twoSum(nums, target):
dct = {}
for i, x in enumerate(nums):
j = target - x
if j in dct:
return [dct[j], i]
else:
dct[x] = i