1.题目描述
问题描述
需要从整数位置x移动到整数位置y。每一步可以将当前位置增加或减少,且每步的增加或减少的值必须是连续的整数(即每步的移动范围是上一步的-1,+0或+1)。首末两步的步长必须是1。求从x到y的最少步数。
输入描述
输入包含两个整数x和y,表示起始位置和目标位置。
输出描述
输出从x到y所需的最小步数。
示例1
输入:x_position = 34,y_position =45输出:6
示例2
输入:x_position = 50, y_position = 30输出:8
难度等级
简单
题目链接
[(代码练习 - MarsCode)]
2.解题思路
因为步长只能加一减一或者不变,所以要步数最少,就要找到最大的步长是多少,因为最后一步步长一定为1,所以步长的列表递增和递减的过程呈对称状,当然递减后可以发现还有几步,但范围都要比最大步长短。 比如第二个示例:两个位置差为20,要找它最小的步数就要找它最大的步长,先减首尾步的1步,也就是20-1×2,然后第二步步长加1,递减时1前面也一定有个2,所以18-2×2,依次类推14-3×2,8-2×4发现刚好为零,最大步数为4,且对称了,因步最小步数为4×2。如果减之后发现剩下的步数小于最大步数,我们只用在递减到剩下步数那个数时,多走一步操作为0的步就行了,因此加一就可以了;如果距离减到负数了,我们就加一个最大步数看这时的距离是不是正数了,再进行上面操作。
先进行准备阶段:
int min=xPosition<yPosition?xPosition:yPosition;//得出小的位置数
int distance = max - min;//存储距离大小
int count = 0;//存储走的步数
int step = 1;//每次走的步长
先考虑距离为0的情况
if(distance==0){
return 0;
}
找最大步长
while (distance>0) {
distance-=2*step;//递增与递减时有一样的时候,一起减去
step++;//步长递增
count+=2;//因为距离减了两次,步数也要加两次
if (distance<=step) {//距离小于最大步长时就可以退出循环了
break;
}
}
上一步把距离减到负数的情况下
while (distance<0) {
distance+=step;//加一步最大步长
count--;//加一步最大步长
if (distance>0) {//距离成正数时退出循环
break;
}
}
上一步距离成正后不等于0且比最大步长小时,再加一步
if (distance!=0) {
count+=1;
}
最后返回步长
3.代码实现
public class Main {
public static int solution(int xPosition, int yPosition) {
// Please write your code here
int max=xPosition>yPosition?xPosition:yPosition;
int min=xPosition<yPosition?xPosition:yPosition;
int distance = max - min;
int count = 0;
int step = 1;
if(distance==0){
return 0;
}
while (distance>0) {
distance-=2*step;
step++;
count+=2;
if (distance<=step) {
break;
}
}
while (distance<0) {
distance+=step;
count--;
if (distance>0) {
break;
}
}
if (distance!=0) {
count+=1;
}
return count;
}
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);
}
}
4.总结
以上是我对这道题的解法,我觉得可能需要思考一下的是怎么计算,有更好的方法希望可以指教,谢谢你观看到这里,祝大家刷题顺利。