语言:python3
v1:轮询
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i] + nums[j] == target:
return [i,j]
结果:超时了,提交失败
v2:建立字典,循环字典
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d = {}
for i in range(len(nums)):
if not nums[i] in d:
d[nums[i]] = i #保存数组位置信息
if target - nums[i] in d:
if d[target - nums[i]] < i: #防止 6-3=3的情况
return [d[target - nums[i]], i]
总结:字典映射结构比for循环效率更