题目描述:
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.
For example:
Given array A =[2,3,1,1,4]
The minimum number of jumps to reach the last index is2. (Jump1step from index 0 to 1, then3steps to the last index.)
思路解析:
- 这个是在版本1的基础上,返回步数,从索引0开始,对应数组中的值就是最大的步数,返回最少走几步,就可以到达数组末尾
- 所以lastcover表示在小于lastcover的位置到lastcover这段路途,走了maxcover即最大的步长。所以步数加1;所以这个时候需要更新lastcover的值
- 只是原来的全局最优现在要分成step步最优和step-1步最优(假设当前步数是step)。当走到超过step-1步最远的位置时,说明step-1不能到达当前一步,我们就可以更新步数,将step+1。时间复杂度仍然是O(n),空间复杂度也是O(1)。参考https://blog.csdn.net/linhuanmars/article/details/21356187/
代码:
public class Solution {
public int jump(int[] A) {
if(A==null||A.length==0)
return 0;
int maxcover =0;
int step = 0;
int lastcover = 0;
for(int i=0;i<=maxcover && i<A.length;i++){
if(i>lastcover){
step++;
lastcover = maxcover;
}
if(A[i]+i>maxcover){
maxcover = A[i]+i;
}
}
if(maxcover < A.length-1)
return 0;
return step;
}
}