Jump Game II
算出能跳到最后一步的最小的步数
For example:
Given array A = [2,3,1,1,4]
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.)
代码
同样用贪心算法 算出局部最优解
public class Solution {
public int jump(int[] nums) {
int sc = 0;
int e = 0; // 这个定义不能去
int max = 0;
for(int i = 0; i < nums.length - 1; i++) {
max = Math.max(max, i + nums[i]);
if( i == e ) { //注意只有当相等时才能赋值
sc++;
e = max;
}
}
return sc;
}
}