找到具有给定总和的三元组

时间:2009-12-15 06:01:37

标签: algorithm

我一直在努力解决这个问题。问题是这样的: -

我们有n ^ 2个数字。我们需要找出是否存在三元组a,b,c使得a + b + c = 0.对于更通用的情况,a + b + c = k。 (k给出)

存在O(n ^ 2log(n))复杂度的解决方案。

非常感谢任何帮助。

感谢

2 个答案:

答案 0 :(得分:3)

要在O(n²logn)中获得此信息,您必须对数字进行排序。找到2个数字的所有组合,并进行二分查找以找到第三个数字。

问题的一般版本的上限要高得多。

答案 1 :(得分:0)

我写了一个粗略的解决方案。

绝对可以在O(n ^ 2)中完成。 你不必对此进行排序。

这是问题的扩展,需要将两个数字相加到x,而诀窍是使用哈希表。

def triplets(l, total):
    """Sum of 3 numbers to get to total 
    Basically an extension of the 2 table 
    """
    l = set( l)
    d = { }

    for i in l:
        remain = total - i

        inside = {}
        for j in l:
            if i == j:
                continue
            inside[j] = remain -j

        d[i] = inside

    good = set()

    for first, dic in d.iteritems():
        for second, third in dic.iteritems():
            if third in l:
                good.add( tuple(sorted([first, second, third])) )

    for each in good: 
        print each

triplets( [2, 3, 4, 5, 6], 3+4+5)

注意:我们可以对三元组使用快速排序方法,即O(1)。