【发布时间】:2019-08-31 17:13:07
【问题描述】:
我从Daily Code逻辑问题开始,收到了第一个,很简单,但我不明白“一次性完成”是什么意思。它只在一行中做到这一点?如果是,那么在这个问题上怎么可能? 这就是问题和我的代码:
##Good morning! Here's your coding interview problem for today.
##This problem was recently asked by Google.
##Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
##For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
##Bonus: Can you do this in one pass?
def equivalent_sum(n,list_of_n):
for x in list_of_n:
for y in list_of_n:
boolean = False
if x != y:
if x + y == n:
boolean = True
print("{} + {} {}".format(x,y,boolean))
l_of_numbers = [2,3,7,10,13,17,21]
equivalent_sum(20,l_of_numbers)
【问题讨论】:
-
“一次通过”表示“遍历列表一次”。但是您的解决方案会多次迭代列表。
-
“一次性完成”在这种情况下可能意味着“只使用一个 for 循环”。
-
一次通过 ==> O(n) 时间复杂度