题目描述:
题目解答:
在Leetcode的Discuss中多数采用贪心算法,就是当前能跳多远就跳多远,而且还存在两种贪心算法,一种是从前往后跳,一种是从后往前跳。
有一个重要的思想是:它既然能跳到前面,也可以稍微退后一点跳,结合下面的FarIndex的更新过程进行思考!
下面是贪心算法的解答的算法:
class Solution {
//采用贪心算法求解,每一次跳到最远,从前往后跳
public int jump(int[] nums) {
int nextIndex=0;
int FarIndex=0;
int steps=0;
for(int i=0;i<nums.length-1;i++){//为什么是nums.length-1呢?因为到了最后一步就不用跳了
FarIndex=Math.max(FarIndex,i+nums[i]);
if(i==nextIndex){
nextIndex=FarIndex;
steps+=1;
}
}
return steps;
}
}
另外一种,从后往前跳的:
这种方法是从后往前找能到达这个地方最左边的位置
public int jump(int[] nums) {
int position = nums.length - 1;
int steps = 0;
while (position != 0) {
for (int i = 0; i < position; i++) {
if (i+nums[i] >= position ) {
position = i;
steps++;
break;
}
}
}
return steps;
}
运行结果:
还可以将这个算法转换成 BFS 问题进行求解,下面是解答方案(网路摘抄):
int jump(int A[], int n) {
if(n<2)return 0;
int level=0,currentMax=0,i=0,nextMax=0;
while(currentMax-i+1>0){ //nodes count of current level>0
level++;
for(;i<=currentMax;i++){ //traverse current level , and update the max reach of next level
nextMax=max(nextMax,A[i]+i);
if(nextMax>=n-1)return level; // if last element is in level+1, then the min jump=level
}
currentMax=nextMax;
}
return 0;
}