45. 跳跃游戏 II

51 阅读1分钟

45. 跳跃游戏 II

中等

相关标签

premium lock icon相关企业

给定一个长度为 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 <= 104
  • 0 <= nums[i] <= 1000
  • 题目保证可以到达 n - 1

题解: 比I难一些在于,最大距离要在一步之内去维护,每一步再更新一次,所以要两个循环。

#include <stdio.h>
#include <stdlib.h>

int max(int a, int b)
{
    return a > b?a:b;
}

int main ()
{
    int size, i, stepreach, newreach, count = 0;
    scanf("%d", &size);
    int* nums = (int*)malloc(sizeof(int) * size);
    for (i = 0;i <= size - 1;i ++)
    {
        scanf("%d", &nums[i]);
    }
    stepreach = nums[0];
    newreach = nums[0];
    i = 0;
    while (newreach < size - 1)
    {
        stepreach = newreach;
        count ++;
        while (i <= stepreach)
        {
            newreach = max(newreach, nums[i] + i);
            i ++;
        }
    }
    printf("%d", count + 1);

    return 0;
}