Find all pairs of integers within an array which sum to a specified value

前端 未结 15 2041
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 08:00

Design an algorithm to find all pairs of integers within an array which sum to a specified value.

I have tried this problem using a hash

15条回答
  •  感动是毒
    2020-12-01 08:35

    Implemented in Python 2.7:

    import itertools
    list = [1, 1, 2, 3, 4, 5,]
    uniquelist = set(list)
    targetsum = 5
    for n in itertools.combinations(uniquelist, 2):
        if n[0] + n[1] == targetsum:
        print str(n[0]) + " + " + str(n[1])
    

    Output:

    1 + 4
    2 + 3
    

提交回复
热议问题