这意味着“检测到的时间复杂度:O(Y-X)”是什么意思?

时间:2019-05-14 06:14:15

标签: c# algorithm loops time-complexity performance-testing

我正在做一些Codility编码实践,结果得到了“检测到的时间复杂度:O(Y-X)”。我不明白这是什么意思。是因为我糟糕且不断循环吗?如何增强或改善性能以摆脱性能不佳的问题?

public static int Solution(int startPoint, int endPoint, int frogJumpPowerDistance)
{
            int jumpCount = 0;

            // AIM: return the number of jumps to reach endPoint

            // CHECK: no jump needed.
            if (startPoint == endPoint) return jumpCount;

            int distanceReach = startPoint + frogJumpPowerDistance;
            jumpCount++;
            if (distanceReach < endPoint)
            {
                //enter checking loop
                do
                {
                    distanceReach += frogJumpPowerDistance;
                    jumpCount++;
                }
                while (distanceReach < endPoint);
            }

            return jumpCount;
}

我希望不会收到超时错误。但是我明白了。

我不确定如何改善代码以解决超时错误。

对于输入(5,1000000000,2),解决方案超出了时间限制。

供您参考,

  1. 所有输入都在[1 ... 1,000,000,000]范围内。

  2. startPoint小于或等于endPoint。

2 个答案:

答案 0 :(得分:4)

我认为“检测到的时间复杂度:O(Y-X)”的意思是,当起点和终点距离较远时,您的代码将花费更长的运行时间。具体来说,相对于开始和结束之间的差异,运行代码所需的时间线性增加。请注意,我假设Y是结尾,X是开头。

您实际上不需要在这里循环。您可以做一些数学运算来找出需要多少跳,并在恒定的时间O(1)中进行。

首先,您需要通过计算起点和终点之间的差来计算必须跳过的距离:

int distance = endPoint - startPoint;

然后,将距离除以跳跃力:

int jumps = distance / frogJumpPowerDistance;

如果distancefrogJumpPowerDistance整除,那么我们可以返回jumps。否则,在我们跳了jumps次之后(这是整数除法!),我们还有一段距离。因此,我们需要再跳一次才能完成它。

if (distance % frogJumpPowerDistance == 0) {
   return jumps;
} else {
   return jumps + 1;
}

编辑:

正如iakobski在评论中建议的那样,也可以只划分一个部分,就像这样:

return (distance - 1) / frogJumpPowerDistance + 1;

答案 1 :(得分:0)

  

我得到了“检测到的时间复杂度:O(Y-X)”。

理论上,您是从起点线性移动到终点,并具有一定的跳变值,但是重要的是会发生什么,如果您必须一次仅用2个步长达到1 Bn?

您提到的问题集是算术级数,其中:

Begin Value = 5End Value = 10^9 (1 billion)Common Difference = 2

使用简单的算术级数公式,可以知道此级数中的元素数(总跳跃数),

a(n) = a(0) + (n-1)*(Common Difference),这里(Common Difference)是您的跳转值frogJumpPowerDistance,简单的替换将建议该值为:

10^9 = 5 + (n-1) * 2 n大约为5亿,而忽略了无关紧要的加减法

  

这是什么意思?

在计算时间复杂度的大O表示法时,虽然我们通过您的循环逻辑进行计算,但是它会在O(N)左右,并且N的值太高,超过5亿。

  

为使O(N)复杂度相同,您可以采取哪些措施使其更快?

  • 增大frogJumpPowerDistance的值,假设您将其设置为1000,N(跳数)将约为100万,比上一个值大幅度减少,依此类推

因此,这个想法要么是对frogJumpPowerDistance的实质改进,以使其成为一种更好的算法,或者如果它很好地使用了建议的公式之一,则可以使用算术级数公式。

在大多数情况下,我们无法使用直接公式来解决数学问题集,它无法在List时间内循环使用O(N)之类的数据结构,如果可能,则可能是O(LogN)您可以在每个关口处减小1/2,假设对数以2为底,但本质在于减小N的值,并将Common differenceJump value增大实质值,从而使算法更快