题目:输出能跳到数组末尾的最小跳数。详见Jump Game
分析:同样,也是贪心。因为当前跳如果能跳到k,那么必然也能跳到小于k的地方,所以贪心是可以的。然后用一个int记录当前跳能到的最大位置,另一个int记录下一跳能到的最大位置,模拟跳的过程:从i=0往前跳,如果当前跳不能到i,而下一跳可以到i,则多跳一步,否则就以i跳更新下一跳的最大距离
答案:
class Solution {
public:
int jump(vector<int>& nums) {
int n = nums.size();
int nextMaxReach = 0;
int currentMaxReach = 0;
int jumpCount = 0;
for (int i = 0; i< n ; i ++){
if (currentMaxReach >=n -1)// we can reach final
return jumpCount;
if (i <= currentMaxReach){// we can reach i
nextMaxReach = max(i+nums[i], nextMaxReach);//update max reach we can do in next jump
printf("round: %d update next reach: %d\n",i,nextMaxReach);
}else{// we can not reach i in this jump
if (i <= nextMaxReach){// but we can reach i in next jump
jumpCount++;
currentMaxReach = nextMaxReach;
nextMaxReach = max(i+nums[i], nextMaxReach);// jump and update
printf("round: %d jump: %d\n",i,currentMaxReach);
}else{
return -1;// we cannot reach i, never
printf("round: %d we can not go further\n",i);
}
}
if (nextMaxReach >=n -1)// we can reach final
return jumpCount+1;
}
return -1;
}
};