繁体   English   中英

如何在列表中找到成对的整数,这些整数加起来为 O(N) 中的目标?

[英]How to find pairs of integers in a list that add up to a target in O(N)?

我有一个输入列表

lst = [2, 4, 3, 6, 5]

如果我说target = 7 ,我想得到

[(0, 4), (1, 2)]

这些是lst中数字对的索引,它们加起来为target (7)。

我们如何使用单个for循环获得预期结果?

这样想:对于您遇到的索引i处的每个数字n ,您需要找到一个包含7 - n的索引j 您可以通过维护以下结构在列表中单次执行此操作:

  • 到目前为止您找到的配对列表
  • 一个7 - n : i的映射,这样当你在索引j处遇到7 - n时,你可以添加对i, j

一种仅使用一个循环的简单方法是

from collections import defaultdict

def find_target(data, target):
    pairs = []
    found = defaultdict(list)
    for i, n in enumerate(data):
        m = target - n
        found[m].append(i)
        if n in found:
            pairs.extend((j, i) for j in found[n])
    return pairs

使用defaultdict保存所有可能重复项的索引列表是确保获得所有可能组合的简单方法。

对于您的具体情况:

>>> find_target([2, 4, 3, 6, 5], 7)
[(1, 2), (0, 4)]

结果按第二个索引排序(因为它决定了一对何时进入列表)。 如果要按第一个索引对其进行排序,可以这样做:

>>> result = find_target([2, 4, 3, 6, 5], 7)
>>> result.sort()
>>> result
[(0, 4), (1, 2)]

或者更浪费,

>>> sorted(find_target([2, 4, 3, 6, 5], 7))
[(0, 4), (1, 2)]

单个列表理解中:按目标值过滤并跳过重复值。

target = 7
lst = [2, 4, 3, 6, 5]

output = [(i1, i2) for i1, j1 in enumerate(lst) for i2, j2 in enumerate(lst) if j1+j2 == target and i1 < i2]
print(output)

或者,为了避免and ,使用切片(连同i2 -index 的移位):

[(i1, i2) for i1, j1 in enumerate(lst) for i2, j2 in enumerate(lst[i1:], start=i1) if j1+j2 == target]

作为单个for 循环。 想法:迭代所有对的“集合”的大小(不使用按距离过滤,如疯狂物理学家的回答):

lst = [2, 4, 3, 6, 5, 1]
target = 7

out = []
n = len(lst)
blk = n-1
loop_counter = 1
c = 0
for i in range(n*(n-1)//2):
    # indices
    a, b = n-blk-1, c % blk + n-blk

    # check condition
    if lst[a] + lst[b] == target:
        out.append((a, b))

    # next iteration
    c+=1
    if c % blk == 0:
        blk -= 1
        c = 0
        loop_counter += 1

print(out)
#[(0, 4), (1, 2), (3, 5)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM