题解—计算从位置 x 到 y 的最少步数|豆包MarsCode AI刷题

119 阅读2分钟

一、solution方法详细分析

1. 初始化阶段

int distance = Math.abs(y_position - x_position);
int nowstep = 2;
int step_account = 1;
int sumstep = 0;
  • 首先,通过Math.abs(y_position - x_position)计算出两个输入坐标的差值的绝对值distance。这个distance的值代表着x到y的距离。

  • 接着,初始化了几个变量:

    • nowstep被初始化为2,它代表相当于已经走了第一步了。
    • step_account初始化为1,它是用于记录步数的变量,因为已经走了第一步所以初始化为1。
    • sumstep初始化为0,它是用于逐步累加步数或者距离,以便最终确定总的步数或者达到目标距离所需的其他相关结果。

2. 特殊情况处理

if (distance == 0) {
    return 0;
} else if (distance == 1) {
    return 1;
} else if (distanc == 2) {
    return 2;
} else if (distance == 3) {
    return 3;
}

这里对distance的几种特殊值进行了单独处理。当distance0时,意味着两个坐标相同,所以返回0步;当distance123时,分别直接返回对应的步数,这是因为每一步都是1。

3. 循环计算阶段

while (sumstep < (distance - 2)) {
    if (step_account % 2 == 1) {
        sumstep += nowstep;
        step_account += 1;
    } else {
        sumstep += nowstep;
        nowstep += 1;
        step_account += 1;
    }
}
  • distance的值不在上述特殊情况范围内时,进入这个循环。循环的条件是sumstep小于distance - 2,因为首尾步长都是1。

  • 在循环内部,根据步数step_account的奇偶性进行不同的操作:

    • 如果step_account是奇数(step_account % 2 == 1),那么将当前的步长nowstep累加到sumstep中,并且步数step_account增加1。这意味着在奇数步时,只是按照当前的步长增加累计的距离相关值ans
    • 如果step_account是偶数(step_account % 2 == 0),不仅将当前步长nowstep累加到sumstep中,还会将步长nowstep自身增加1,同时步数step_account也增加1。这说明在偶数步时,除了按照当前步长增加累计值外,还会适当增加下一次的步长,可能是为了更快地接近目标距离(由distance表示)。

4. 返回结果

return t + 1;

循环结束后,返回t + 1作为最终结果。这里加1的原因是因为在循环结束时,实际的步数可能还需要再进行+1。

二、main方法分析

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);
}

综上所述,这段代码可以实现两个输入坐标计算最小步数的功能,通过特殊情况处理和循环计算逐步确定最终的返回值,并在main方法中进行了简单的测试验证。