45. Jump Game II
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.
题意:给一个数组,数组中每个元素代表的是当前位置可以跳的步数。 问到达数组最后的index所需要的最少步数。 这个题我们需要贪一个范围, 求出没每一步的能到达的最远位置。所以需要一个变量记录上一步可达的最远位置。然后遍历里面所有数值,求出下一步可达的最远范围。直到覆盖目标 index
代码
class Solution {
public int jump(int[] nums) {
if(nums.length <= 1) return 0;
int step = 1, right = 0;
right = nums[0] + 0;
if(right >= (nums.length - 1)) return step;
int p = 0;
int lastdist = right;
while(right < nums.length - 1) {
while(p < nums.length && p <= lastdist) {
right = Math.max(right, nums[p] + p);
p++;
}
lastdist = right;
step++;
if(right >= (nums.length - 1)) return step;
}
return -1;
}
}