LeetCode:79.跳跃游戏Ⅱ
目录
1.跳跃游戏Ⅱ
1.跳跃游戏Ⅱ
这道题与上一道不同在于肯定可以跳跃过去,计算步数,我们用一个end来保存边界,如果说已经走到了end的话,想要再向前走就必须要再跳一次
每次在上次能跳到的范围(end)内选择一个能跳的最远的位置(也就是能跳到maxpos位置的点)作为下次的起跳点
class Solution {
public:int jump(vector<int>& nums) {int n = nums.size(), maxpos = 0, end = 0, step = 0;for(int i = 0; i < n - 1; i++){if(i <= maxpos){maxpos = max(maxpos, i + nums[i]);if(i == end){end = maxpos;step++;}}}return step;}
};