sumOfTwo Time Limit Exceeded CodeFights采访练习

时间:2017-02-20 05:01:16

标签: python optimization

我正在尝试CodeFights.com上的sumOFTwo挑战,但我无法完成它以查看解决方案。我的所有测试都进行到第15次隐藏测试,并表示超过了时间限制。

挑战是 - 你有两个整数数组,a和b,以及一个整数目标值v。确定是否有一对数字,其中一个数字来自a,另一个数字来自b,可以添加如果存在这样的一对,则返回true,否则返回false。

我的代码是 -

def sumOfTwo(a,b,v):
    a.sort()
    b.sort()

    if(0 in a and v in b):
        return True
    elif(v in a and 0 in b):
        return True
    else:
        for i in a:
            for j in b:
                if(i + j == v):
                    return True
    return False

我知道它可以缩减到大约6行代码,但我不断添加行可以帮助代码更快地完成。我还缺少任何其他优化措施。

4 个答案:

答案 0 :(得分:6)

您可以将其中一个列表转为spring.mail.host = smtp.office365.com spring.mail.username = my.email@company.com spring.mail.password = password spring.mail.port = 587 spring.mail.properties.mail.smtp.auth = true spring.mail.properties.mail.smtp.starttls.enable = true ,迭代其他列表,看看set中是否存在v - value_from_list

set

输出:

def sumOfTwo(a,b,v):
    b = set(b)

    return any(v - x in b for x in a)

print(sumOfTwo([3, 6, 7], [2, 1], 9))
print(sumOfTwo([3, 6, 7], [2, 1], 10))
print(sumOfTwo([3, 6, 7], [2, 1], 4))
print(sumOfTwo([3, 6, 7], [2, 1], 3))

O(n)中的上述时间复杂度。

答案 1 :(得分:0)

这就是我所拥有的。它通过了所有测试,包括隐藏,但是在四个隐藏测试中需要很长时间。

def sumOfTwo(a, b, v):
  for i in a:
    if((v-i) in b):
      return True
  return False

@ niemmi的答案通过了时间限制部分。我不知道集合比数组/列表快。谢谢,很高兴知道。如果我在b=set(b)循环之前添加for,则会传递。{/ p>

答案 2 :(得分:0)

尝试一下:

function sumOfTwo(a, b, v) {
if(a.length==0)return false;
if(b.length==0)return false;
for(var i=0; i<a.length; i++){
     if(b.indexOf(v-a[i])>0){
        return true;
    }
}
return false;}

答案 3 :(得分:0)

这是我在Python中解决的方法:

 def sumOfTwo(a, b, v):
        #No need to iterate a huge list, if the other list is empty
        if not a or not b:
            return False
        
        #kill duplicates
        b = set(b)
        
        #iterate through list a to look if the wanted difference is in b
        for x in a:
            if (v-x) in b:
                return True
        return False