计算从位置 x 到 y 的最少步数
问题描述
小F正在进行一个 AB 实验,需要从整数位置 x 移动到整数位置 y。每一步可以将当前位置增加或减少,且每步的增加或减少的值必须是连续的整数(即每步的移动范围是上一步的 -1,+0 或 +1)。首末两步的步长必须是 1。求从 x 到 y 的最少步数。
输入描述
输入包含两个整数 x 和 y,表示起始位置和目标位置。
输出描述
输出从 x 到 y 所需的最小步数。
测试样例
样例1:
输入:
x_position = 12, y_position = 6
输出:4
样例2:
输入:
x_position = 34, y_position = 45
输出:6
样例3:
输入:
x_position = 50, y_position = 30
输出:8
样例4:
输入:
x_position = 0, y_position = 0
输出:0
解题思路
-
计算初始距离:
首先通过
Math.abs(x_position - y_position)计算出x_position和y_position之间的绝对值距离,存储在distance变量中。这个距离将作为后续计算步数的重要依据。
int distance =Math.abs(x_position - y_position);
-
初始化变量:
-
定义三个个用于计算步数的变量:
total:用于累计已经走过的 “路程”,初始化为 0。steps:用于记录已经走的完整步数,初始化为 0。current_step:表示当前一步所走的 “路程”,初始化为 1。
-
-
循环计算步数:
-
进入一个
while循环,只要total小于distance,就会持续执行循环体内容。-
在每次循环中:
- 首先将
steps加 1,表示完成了一步。 - 然后将
current_step累加到total中,更新已经走过的总路程。
- 首先将
-
接着进行条件判断:
-
如果
(total + current_step + 1) * 2 <= distance,说明按照当前的增长趋势(每次增加current_step),接下来两步(乘以 2 是考虑接下来两步的情况)所走的路程仍然小于等于剩余的距离distance,那么就将current_step增加 1,即加大下一步要走的路程。 -
如果不满足上述条件,说明已经接近目标距离或者已经超过目标距离(在接下来两步内),就需要进一步判断:
- 如果
distance == total * 2,这意味着刚好走了偶数步就到达了目标距离,此时返回steps * 2。 - 如果
(distance - 2 * total) <= (current_step + 1),表示剩余的距离小于等于当前一步再加上一步(可以理解为再走一步或者半步就能到达目标距离),此时返回steps * 2 + 1。 - 如果以上两个条件都不满足,那就说明需要再走两步才能到达目标距离,所以返回
steps * 2 + 2。
- 如果
-
-
-
-
最终返回结果:
- 如果在
while循环结束后还没有返回结果(这种情况可能是distance恰好等于total),就直接返回steps。
- 如果在
解题代码
public class Main {
public static int solution(int x_position, int y_position) {
//**计算初始距离**:
int distance =Math.abs(x_position - y_position);
//**初始化变量**:
int total=0;
int steps=0;
int current_step=1;
//**循环计算步数**:
while(total<distance)
{
steps+=1;
total+=current_step;
if((total+current_step+1)*2<=distance )
{
current_step++;
}
else{
if(distance==total*2)
{
return steps*2;
}
else if((distance-2*total)<=(current_step+1))
{
return steps*2+1;
}
else {
return steps*2+2;
}
}
}
return steps;
}
public static void main(String[] args) {
// You can add more test cases here
System.out.println(solution(12, 6) == 4);
System.out.println(solution(34, 45) == 6);
System.out.println(solution(50, 30) == 8);
System.out.println(solution(0, 0) == 0);
}
}
总结
先计算目标距离 d = |x - y|,接着初始化步数 steps 为 0、累计移动距离 total 为 0、首步步长 current_step 为 1,然后在循环中每步让 steps 加 1 且把 current_step 累加到 total,若 (total + current_step + 1)×2 ≤ d 就使 current_step 加 1,之后根据距离判断情况,若 d = total×2 则返回 steps×2,若 (d - 2×total) ≤ (current_step + 1) 则返回 steps×2 + 1,否则返回 steps×2 + 2,若 x = y(即 d = 0)则直接返回 0