这是我参与「第七届青训营 」伴学笔记创作活动的第1天
今天的代码练习题目是:
计算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
题目解析
从x走到y,其实就是从步伐大小从1开始走,最后一步也必须为1,每一步之间呢,可以+1,0,和-1,如果说想要最小步数,这个步伐肯定要迈的大,我的代码呢,遵循一个原则,就是第一步肯定为1,接下来每一步有三种选择,假设步伐为x,一个是x + 1,一个是x,一个是x - 1,在优先级上x + 1 > x > x - 1,在是否合规上采取走下一步的时候,必须保证剩余的距离,可以降到 1 ,也就是说先 x + 1,但是剩下的距离必须大于等于 x~1的和,如果不可以那就尝试 x,剩下的距离大于等于 x - 1 ~ 1 的he,x - 1也是如此,直至走到y。
代码如下:
public class Main { public static int sum(int x) { if (x <= 0) { return 0; } int res = 0; for (int i = 1; i <= x; i++) { res += i; } return res; }
// Calculate the minimum steps from x to y
public static int solution(int x, int y) {
if (x > y) {
int temp = x;
x = y;
y = temp;
}
int l = 0, r = y - x;
int step = 0;
int stepDistance = 0;
while (l < r) {
if (step == 0) {
stepDistance = 1;
step = 1;
l += stepDistance;
continue;
}
int step1 = stepDistance + 1;
int step2 = stepDistance;
int step3 = stepDistance - 1;
if (l + step1 < r) {
int m = l + step1;
int s = sum(step1 - 1);
if ((r - m) >= s) {
l = m;
step++;
stepDistance = step1;
continue;
}
}
if (l + step2 <= r) {
int m = l + step2;
int s = sum(step2 - 1);
if ((r - m) >= s) {
l = m;
step++;
stepDistance = step2;
continue;
}
}
if (l + step3 <= r) {
int m = l + step3;
int s = sum(step3 - 1);
if ((r - m) >= s) {
l = m;
step++;
stepDistance = step3;
continue;
}
}
}
return step;
}
public static void main(String[] args) {
// Add your test cases here
System.out.println(solution(6, 7) == 1); // Should print true
System.out.println(solution(12, 6) == 4); // Should print true
System.out.println(solution(34, 45) == 6); // Should print true
System.out.println(solution(50, 30) == 8); // Should print true
}
}
学习方法与心得
写代码,是一场充满挑战与惊喜的旅程。
起初,面对复杂的需求和陌生的代码逻辑,满心忐忑。但经过一段时间的学习,随着一行行代码的敲下,思路逐渐清晰。每一次成功运行,都像是突破了一道关卡,带来满满的成就感。调试过程虽艰辛,却也让我对代码的理解更加深刻。我享受与朋友一起探讨与写下代码时,思维碰撞出的不同火花,也学会了从不同角度优化代码。从此于我而言,写代码不再是枯燥的任务,而是一种创造,一种用逻辑和智慧构建世界的方式。另外,AI刷题功能与其他学习资源相结合让我更加便利的达到了很好的学习效果,希望大家都来尝试与参与!
利用AI写代码能极大提高效率。它可以快速给出代码框架,对于常见功能,比如文件读取、简单算法实现等,能节省大量时间。而且当遇到编程难题时,AI的多种思路可能会启发我们。但不能完全依赖,因为其可能存在理解偏差。
清晰描述需求,包括功能、输入输出格式等。如果是特定语言,如Python,要指明。逐步引导AI生成代码,对不满意的部分,要求它修改。同时,要自己理解代码逻辑,避免引入潜在的错误。