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
。
每走一轮相当于走一步。
算法的关键步骤如下:
-
初始化变量:
start
: 表示当前步骤中考虑跳跃的起始索引。max_reach
: 表示当前步骤能够到达的最远索引。next_max_reach
: 表示下一步能够到达的最远索引。step
: 用于记录到达数组末尾所需的步数。
-
遍历数组:
- 使用一个
while
循环,条件为max_reach
小于数组的最后一个索引(nums.size() - 1
)。 - 在每一步中,增加
step
的计数,并更新next_max_reach
。 - 通过内部的
for
循环,遍历从start
到max_reach
之间的所有索引。 - 在每次迭代中,计算并更新可以到达的最远索引
next_max_reach
。 - 循环结束后,更新
start
和max_reach
为下一轮迭代的值。
- 使用一个
-
返回结果:
- 当
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;
}
};