题目:Two Sum
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
第一步:用 zip 函数做一个字典,将nums中数字与index联系起来:
In [33]: dictionary = dict(zip(nums, list(range(0, len(nums)))))
In [34]: dictionary
Out[34]: {2: 0, 7: 1, 11: 2, 15: 3}
第二步:循环将 target 减去 nums 中的 value, 得到一个subvalue, 如果这个subvalue在字典里面, 就返回 value和subvalue的 index
完整程序如下:
calss Solution():
def twosum(nums, target):
dictionary = dict(zip(nums, list(range(0, len(nums)))))
for index, value in enumerate(num):
subvalue = target - value
if sub in dic:
return [index, dictionary[subvalue]]
else:
continue
也可循环生成字典(此种解法是别人写的,代码里面有其详细地址),此种解法如下:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dic = dict()
for index,value in enumerate(nums):
sub = target - value
if sub in dic:
return [dic[sub],index]
else:
dic[value] = index #此处循环生成字典,效果和我上面程序的dictionary一样
作者:石晓文的学习日记
链接:https://www.jianshu.com/p/b71fc7307e42
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。