欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

45. 跳跃游戏 II

程序员文章站 2022-05-20 14:05:56
...

给定一个非负整数数组,你最初位于数组的第一个位置。

数组中的每个元素代表你在该位置可以跳跃的最大长度。

你的目标是使用最少的跳跃次数到达数组的最后一个位置。

示例:

输入: [2,3,1,1,4]
输出: 2
解释: 跳到最后一个位置的最小跳跃数是 2。
从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。

代码

int Max(int a,int b){
    return a>b?a:b;
}
class Solution {
public:
    int jump(vector<int>& nums) {
        int numsSize=nums.size();
       int count = 0, max = 0,nextMax=0;
    for (int i = 0; i <= max && i < numsSize - 1; i++) {
        nextMax = Max(nextMax, i + nums[i]);
        if (i == max) {
            max = nextMax;
            count++;
            if(max>=numsSize-1) return count;
        }
    }
    return 0;
    }
};
相关标签: 领扣