【问题标题】:What means "do this in one pass"?什么是“一次性完成”?
【发布时间】: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) 时间复杂度

标签: python logic


【解决方案1】:

一次 ==> O(n) 时间复杂度

您将遍历列表一次:

passed_nums = set() 
numbers = [2,3,7,10,13,17,21] 
k = 17 

def equivalent_sum(numbers):
    for num in numbers:
       diff = k - num
       if diff in passed_nums:
           return True
       passed_nums.add(num)
    return False

equivalent_sum(numbers)

或者你可以使用:

num_set = set(numbers)
any(k - e in num_set for e in numbers)  

内置函数更快,因为它们在 C 代码上运行

【讨论】:

    猜你喜欢
    • 2015-04-23
    • 1970-01-01
    • 2012-11-17
    • 1970-01-01
    • 2021-10-16
    • 2014-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多