Leetcode 1.两数之和 By Python

思路

很容易想到的方法是二重循环遍历一遍,但是会很慢

把加法变减法可以大大加速

代码

class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
book = {}
for key,value in enumerate(nums):
if value not in book:
delta = target - value
book[delta] = key #对应的key和value分别是差值和索引
else:
return [book[value], key]

PS.二重循环是7000+ms,上面的代码只要40ms

上一篇:2019 校内赛 RPG的天赋分支(贪心)


下一篇:Hadoop自定义分组Group