class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型vector
* @return int整型
*/
int minJumpStep(vector<int>& nums) {
// write code here
int n = nums.size();
if (n == 0) return -1;
if (n < 2) return 0; // 数组长度为 0 不用跳,或者长度为 1,起点就是终点,不用跳
int jumps = 0, currentEnd = 0, farthest = 0;
for (int i = 0; i < n - 1; ++i) {
// 更新能到达的最远距离
farthest = max(farthest, i + nums[i]);
if (i >= farthest) return -1;
// 已经可以到达最后一个位置
if (currentEnd >= n - 1) break;
// 当到达当前跳数能到的最远距离时
if (i == currentEnd) {
// 如果最远距离超过或者刚好到最后一个位置,直接返回
if (farthest >= n - 1) return jumps + 1;
// 更新当前跳数能到达的最远距离
currentEnd = farthest;
jumps++;
}
}
// 如果最后一个位置可达,返回跳数,否则返回 -1
return farthest >= n - 1 ? jumps : -1;
}
};