Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
Example:
Input: [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2.
Jump 1 step from index 0 to 1, then 3 steps to the last index.
Note:
You can assume that you can always reach the last index.
/****************************************************************/
一道非常明显的动态规划题。一开始我很天真地用动态规划从后往前计算步数,最后发现果然有一个用例超时了……
然后我用了一个非常naive的方法:把已经算出来步数的点按从小到大排序,这样每次计算新点,只需要在这个排序了的数组中找到最小的可达点就可以了。最后勉强ac,很丢人的是运行时间比95%的人要慢……
看了一下别人的代码,原来很简单,题干里甚至有提示,只是我之前没看……就是应该从开始考虑在k步内能够到达的最远距离,而不是从结尾开始考虑每个点到达结尾的最小步数。这个高效方法的代码我就不放了,放一下我的低效代码,做一个记录:
public int jump(int[] nums) {
int MinJump[] = new int[nums.length];
int SortedStep[] = new int[nums.length];
for(int i =0; i<nums.length-1;i++)
{
MinJump[i] = Integer.MAX_VALUE-nums.length;
SortedStep[i] = 0;
}
MinJump[nums.length-1] = 0;
SortedStep[0]= nums.length-1;
int MinPoint = 0;
for(int j=nums.length-2;j>=0;j--)
{
for(int k = 0;k<nums.length-1-j;k++)
{
if(SortedStep[k]-j<=nums[j])
{
MinJump[j] = 1+MinJump[SortedStep[k]];
break;
}
}
int i = 0 ;
for(i = nums.length-j-2; i>0;i--)
{
if(MinJump[SortedStep[i]]>MinJump[j])
{
SortedStep[i+1]=SortedStep[i];
}
else break;
}
SortedStep[i+1] = j;
}
/***for(int j = nums.length-2;j>=0;j--)
{
for(int k = 1;k<=nums[j] && k+j<nums.length;k++)
{
if(1+MinJump[j+k]<MinJump[j])
MinJump[j] = 1+MinJump[j+k];
}
}***/
return MinJump[0];
}
本文探讨了一道经典的动态规划问题——如何在给定的非负整数数组中,以最少的跳跃次数达到数组的末尾。文章分享了一种从后向前计算的初始尝试,并通过排序优化了算法效率。
1028

被折叠的 条评论
为什么被折叠?



