python - 为什么我这次采访的算法不是最佳方法?

标签 python algorithm subset-sum

Given a list of integers, l = [1,5,3,2,6] and a target t = 6, return true if the list contains two distinct integers that sum to the target

我在 Python 技术面试中被问到这个问题,导致我没有通过。我的回答是:

def two_Sum(l, target):
  for num in l:
    for secondNum in l:
      if num != secondNum:
        if num + secondNum == target:
          return True

我得到的反馈是我的解决方案“不是最佳的”。请帮助我理解为什么这不是最佳解决方案,并详细解释对于这种情况什么是最佳解决方案!

最佳答案

您的解决方案有一个迭代列表的嵌套循环,这意味着它的时间复杂度为 O(n^2) - 空间复杂度为 O(1),因为您不这样做迭代期间不需要存储任何数据。

像这样降低到 O(n) 时间复杂度是可能的,但代价是增加到 O(n) 空间复杂度:

def two_sum(l, target):
    s = set(l)
    for n in l:
        delta = target - n
        if delta != n and delta in s:
            return True
    return False

作为一个微小的改进,您甚至可以避免遍历整个列表,但它仍然是O(n):

def two_sum(l, target):
    seen = set()
    for n in l:
        delta = target - n
        if delta != n and delta in seen:
            return True
        seen.add(n)
    return False

关于python - 为什么我这次采访的算法不是最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47545339/

相关文章:

javascript - 在不使用递归的情况下改进连续范围的子集和算法

javascript - 将元素与总和列表匹配

python - 在 NumPy 中查找特定长度的连续重复

algorithm - 在有序简单列表中插入元素的最有效算法是什么

c++ - 2个给定数字之间的分数密度

algorithm - 计算总和等于 k ​​的子集数

python - conv2d 之后的 PyTorch CNN 线性层形状

python - 自动特征选择 - Sklearn.feature_selection

python - python 中的正则表达式

c++ - 使用迭代器 c++ 删除对象类型的 vector 元素