一、问题
一只小青蛙想去马路的另一边。青蛙当前位于位置X,并且想要到达大于或等于Y的位置。小青蛙始终跳固定距离D。
计算小青蛙达到目标所必须执行的最小跳数。
编写一个函数:
类Solution {public int solution(int X,int Y,int D); }
给定三个整数X,Y和D,则返回从位置X到等于或大于Y的位置的最小跳转次数。
例如,给定:
X = 10
Y = 85
D = 30
该函数应返回3,因为青蛙的位置如下:
第一次跳跃后,位置10 + 30 = 40
第二次跳跃后,位置10 + 30 + 30 = 70
第三跳之后,位置10 + 30 + 30 + 30 = 100
针对以下假设编写有效的算法:
X,Y和D是[ 1 … 1,000,000,000 ] 范围内的整数;
X≤Y。
二、思路
思路一
每次跳一步,累加一次距离,判断是否达到目的地
采用的是加法
这种方法的性能不好
代码
public class Solution {
/**
* @Description:
* @param: [k, X, Y] X初始位置 Y目标 D 每一步的距离
* @return: int 跳的次数
* @date: 2019/11/30 11:26
*/
public int solution(int X, int Y, int D) {
// write your code in Java SE 8
int count = 0;
Y = Y - X;
while (Y > 0) {
Y = Y - D;
count++;
}
return count;
}
}
思路二
直接判断算出需要多少步
采用的是乘法
这种方法的性能好
/**
* @description:这种解法性能好,用的是乘法
* @author: htb
* @createDate: 2019/11/30
* @version: 1.0
*/
public class Solution {
/**
* @Description:
* @param: [k, X, Y] X初始位置 Y目标 D 每一步的距离
* @return: int 跳的次数
* @date: 2019/11/30 11:26
*/
public int solution(int X, int Y, int D) {
//剩余的距离
int leftover=Y-X;
//余数
int toReturn=leftover/D;
if ((leftover%D)>0){
toReturn+=1;
}
return toReturn;
}
}