首页 > 解决方案 > 如何修复“Codility FrogJump”算法?

问题描述

在 Codility 上,有一个计算青蛙到达 Y 位置所需的最少跳跃次数的问题。

问题如下:

A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a fixed distance, D.

Count the minimal number of jumps that the small frog must perform to reach its target.

given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y.

For example, given:

  X = 10
  Y = 85
  D = 30
the function should return 3, because the frog will be positioned as follows:

after the first jump, at position 10 + 30 = 40
after the second jump, at position 10 + 30 + 30 = 70
after the third jump, at position 10 + 30 + 30 + 30 = 100

我已经“解决”了这个问题并得到了“3”,就像在这个例子中一样。然而,当我提交我的代码时,我只得到 11% 并且除了示例之外的所有测试都失败了。

这是我的代码

int count = 0;

while(X <= Y){
X += D;
count++;
}       

return count;

在我的代码中,我基本上计算了到达 Y 所需的跳跃次数,这是青蛙想要到达的位置。我没有正确理解这个问题?如果是这样,我错过了什么?

标签: javaalgorithm

解决方案


为什么在这里使用任何循环,循环是一件昂贵的事情。只需一行答案

function solution(X,Y,D) {
    return Math.ceil((Y-X)/D);
}

推荐阅读