给定一个长度为 n 的 0 索引整数数组 nums。初始位置在下标 0。
每个元素 nums[i] 表示从索引 i 向后跳转的最大长度。换句话说,如果你在索引 i 处,你可以跳转到任意 (i + j) 处:
0 <= j <= nums[i]且i + j < n
返回到达 n - 1 的最小跳跃次数。测试用例保证可以到达 n - 1。
示例 1:
输入: nums = [2,3,1,1,4] 输出: 2 解释: 跳到最后一个位置的最小跳跃数是2。 从下标为 0 跳到下标为 1 的位置,跳1步,然后跳3步到达数组的最后一个位置。
示例 2:
输入: nums = [2,3,0,1,4] 输出: 2
提示:
1 <= nums.length <= 1040 <= nums[i] <= 1000- 题目保证可以到达
n - 1
题解:
class Solution {
public int jump(int[] nums) {
//计算当前索引能到达的最大位置
int maxIndex = 0;
//之前索引能到达的最大值,如果这个值等于索引了,代表该跳一步了,然后更新它
int end = 0;
//跳的步数
int ans = 0;
//最后一个值不需要访问,因为前面maxIndex肯定能达到最后一个,要不然直接为0
for(int i = 0;i<nums.length-1;i++){
maxIndex = Math.max(maxIndex,nums[i]+i);
if(i == end){
end = maxIndex;
ans++;
}
}
return ans;
}
}

