题目:
给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
示例:
输入: [2,3,1,1,4] 输出: 2 解释: 跳到最后一个位置的最小跳跃数是2
。 从下标为 0 跳到下标为 1 的位置,跳1
步,然后跳3
步到达数组的最后一个位置。
这道题,直接想到的办法如下:但是运行时间有点儿长。
package test;
public class LC45Try1
{
public int jump(int[] nums)
{
int len = nums.length;
int[] dp=new int[len];
for(int i=0;i<len;i++){
dp[i]=i;
}
for(int i=0;i<len;i++){
int t= nums[i];
for(int j=1;j<=t;j++){
if(i+j==len){
break;
}
if(dp[i+j]>dp[i]+1){
dp[i+j]=dp[i]+1;
}
}
}
return dp[len-1];
}
public static void main(String[] args)
{
LC45Try1 t = new LC45Try1();
int[] nums = new int[]{2,3,1,1,4};
System.out.println(t.jump(nums));
}
}
添加数组,但运行时间有点长了,于是我就想别的办法,你可以画图,算出跳一次,能走的最远距离,跳两部能走的最远距离,依次。代码如下:
package test;
public class LC45Try2
{
public int jump(int[] nums)
{
int len = nums.length;
int max=nums[0];//记录下次能走的最远的距离
int count=0;//走的次数
int tag=nums[0];//这次能走的最远距离
for(int i=1;i<len;i++){
if(max>=len-1){
return count+1;
}
for(int j=i;j<=tag;j++){
int t=j+nums[j];
if(t>max){
max=t;
}
}
i=tag;
tag=max;
count++;
}
return count;
}
public static void main(String[] args)
{
LC45Try2 t = new LC45Try2();
int[] nums = new int[]{7,0,9,6,9,6,1,7,9,0,1,2,9,0,3};
System.out.println(t.jump(nums));
}
}
但我觉得,我写的太丑了,这是别人写的美的:
package test;
public class LC45Try3
{
// 虽然运行时间一样,但还是觉得人家的简单
public int jump(int[] nums)
{
if (nums == null || nums.length < 2)
return 0;
int jumps = 0;
int curEnd = 0;
int curMax = 0;
for (int i = 0; i < nums.length - 1; i++)
{
curMax = Math.max(curMax, nums[i] + i);
if (i == curEnd)
{
jumps++;
curEnd = curMax;
}
}
return jumps;
}
}
但也许还是第二种比较容易理解。哈哈