代码战斗循环tunel Q2

2024-05-03 05:05:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我无法通过这个问题的隐藏测试。有人能告诉我我的代码有什么问题吗?在

错误消息是:

"Execution time limit exceeded on test 7: Program exceeded the execution time limit. Make sure that it completes execution in a few seconds for any possible input."

我的代码:

def countSumOfTwoRepresentations2(n, l, r):
    c=0
    for i in range(l,r+1):
        for j in range(l,i+1):
            if(i+j==n):
                c+=1
    return(c)

Tags: the代码intest消息fortimeon
2条回答

我想你的问题是:

Given integers n, l and r, find the number of ways to represent n as a sum of two >integers A and B such that l ≤ A ≤ B ≤ r.

在代码中添加2个for循环可能会增加代码的时间复杂性,因为从您的角度来看,这是一种幼稚的方法。你应该试试这个:

def countSumOfTwoRepresentations(n,l,r):
    result = 0
    for a in range(1,r+1):
        b = n - a
        if(b >= l and b <= r and b >= a):
            result+=1
    return result

在这个存储库中,您可以找到代码战斗街机解决方案

https://github.com/tigranv/Code_Fights_Solutions

int countSumOfTwoRepresentations2(int n, int l, int r) {

    int count = 0;

    for(int i = l; i<=r; i++)
    {
      for(int j = i; j<=r&&n-j>=l; j++)
    {
     if(i+j == n)  count++;
    }  

    }

    return count;
}

相关问题 更多 >