标签:try example sum 时间复杂度 ret 时间 int 列表 for
You are given a list of numbers, and a target number k. Return whether or not there are two numbers in the list that add up to k.
Example:
Given [4, 7, 1 , -3, 2] and k = 5,
return true since 4 + 1 = 5.
Try to do it in a single pass of the list.
使用一个字典储存每一个遍历到的元素。
只需遍历一次列表,对每个元素判断 k 减去它的差是否已经在字典中即可。
时间复杂度 O(n).
def two_sum(list, k):
d = {}
for num in list:
other = k - num
if other in d:
return True
else:
d[num] = 1
return False
print two_sum([4,7,1,-3,2], 5)
# True
标签:try example sum 时间复杂度 ret 时间 int 列表 for
原文地址:https://www.cnblogs.com/new-start/p/11657974.html