【LeetCode 面试经典150题】45. Jump Game II 跳跃游戏II

45. Jump Game II

题目大意

You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0].

Each element nums[i] represents the maximum length of a forward jump from index i. In other words, if you are at nums[i], you can jump to any nums[i + j] where:

0 <= j <= nums[i] and
i + j < n
Return the minimum number of jumps to reach nums[n - 1]. The test cases are generated such that you can reach nums[n - 1].

中文释义

给定一个从0开始索引的整数数组 nums,其长度为 n。你最初位于 nums[0]

数组中的每个元素 nums[i] 表示从索引 i 开始向前跳跃的最大长度。换句话说,如果你在 nums[i],你可以跳到任何 nums[i + j],其中:

0 <= j <= nums[i] 且
i + j < n
返回到达 nums[n - 1] 的最小跳跃次数。测试用例保证你能到达 nums[n - 1]

Example

Example 1:

  • Input: nums = [2,3,1,1,4]
  • Output: 2
  • Explanation: 到达最后一个索引的最小跳跃次数是2。从索引0跳1步到索引1,然后跳3步到最后一个索引。

Example 2:

  • Input: nums = [2,3,0,1,4]
  • Output: 2

Constraints

  • 1 <= nums.length <= 10^4
  • 0 <= nums[i] <= 1000
  • 保证你能到达 nums[n - 1]

解题思路

算法描述

此代码解决了在给定的整数数组中计算到达数组末尾所需的最小跳跃次数的问题。

将这个遍历过程分为step轮,每一轮将一些可以到达的点搜罗进来,并且记录可以到达的最远的点 next_max_reach
在每轮结束的时候更新max_reach
每走一轮相当于走一步。

算法的关键步骤如下:

  1. 初始化变量:

    • start: 表示当前步骤中考虑跳跃的起始索引。
    • max_reach: 表示当前步骤能够到达的最远索引。
    • next_max_reach: 表示下一步能够到达的最远索引。
    • step: 用于记录到达数组末尾所需的步数。
  2. 遍历数组:

    • 使用一个 while 循环,条件为 max_reach 小于数组的最后一个索引(nums.size() - 1)。
    • 在每一步中,增加 step 的计数,并更新 next_max_reach
    • 通过内部的 for 循环,遍历从 startmax_reach 之间的所有索引。
    • 在每次迭代中,计算并更新可以到达的最远索引 next_max_reach
    • 循环结束后,更新 startmax_reach 为下一轮迭代的值。
  3. 返回结果:

    • max_reach 大于或等于数组的最后一个索引时,循环结束,返回 step 作为到达数组末尾所需的最小步数。

代码示例

class Solution {
public:
    int jump(vector<int>& nums) {
        int start = 0, max_reach = 0, next_max_reach = 0, step = 0;
        while (max_reach < nums.size() - 1) {
            step++;
            for (int i = start; i <= max_reach; i++) {
                next_max_reach = max(next_max_reach, i + nums[i]);
            }
            start = max_reach + 1;
            max_reach = next_max_reach;
        }
        return step;
    }
};
  • 9
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值