刷题-力扣-45. 跳跃游戏 II

45. 跳跃游戏 II

题目链接

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/jump-game-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题目描述

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

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

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

假设你总是可以到达数组的最后一个位置。

示例 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

题目分析

  1. 根据题目描述从数组第一个位置跳跃到数组最后一个位置需要的最少次数
  2. 参考力扣官方题解正向查找可到达的最大位置

代码

class Solution {
public:
    int jump(vector<int>& nums) {
        int needStep = 0;
        int maxPath = 0;
        int endStep = 0;
        for (int i = 0; i < nums.size() - 1; ++i) {
            if (maxPath >= i) {
                maxPath = max(maxPath, i + nums[i]);
                if (i == endStep) {
                    endStep = maxPath;
                    ++needStep;
                }
            }
        }
        return needStep;
    }
};
原文地址:https://www.cnblogs.com/HanYG/p/15243235.html