Leetcode 45.跳跃游戏II

题目要求

  • 给定一个长度为 n 的 0 索引整数数组 nums。初始位置为 nums[0]。

  • 每个元素 nums[i] 表示从索引 i 向后跳转的最大长度。换句话说,如果你在 nums[i] 处,你可以跳转到任意 nums[i + j] 处:

    • 0 <= j <= nums[i]
    • i + j < n
  • 返回到达 nums[n - 1] 的最小跳跃次数。生成的测试用例可以到达 nums[n - 1]。

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

示例 2:
输入: nums = [2,3,0,1,4]
输出: 2

不仅关注覆盖范围,还要关注跳数

思路:

首先从起点跳一步,然后计算当前的的最大覆盖范围
如果当前范围已经可以发到终点,那说明只需要跳一次就可以到达终点
如果当前范围不包含终点,那么就说明还需要再跳,之后就从当前的覆盖范围内再计算最大的覆盖范围
以此类推

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public int jump(int[] nums) {
if (nums == null || nums.length == 0 || nums.length == 1) {
return 0;
}
//记录跳跃的次数
int count=0;
//当前的覆盖最大区域
int curDistance = 0;
//最大的覆盖区域
int maxDistance = 0;
for (int i = 0; i < nums.length; i++) {
//在当前可覆盖区域内更新最大的覆盖区域
maxDistance = Math.max(maxDistance,i+nums[i]);
//如果当前覆盖的最大区域已经可以到达终点了,直接返回跳跃次数
if (maxDistance>=nums.length-1){
count++;
break;
}
//如果i==curDistance,说明当前的覆盖区域中可到达的最大位置也没法到达终点,还需要继续往后跳
if (i==curDistance){
curDistance = maxDistance;
count++;
}
}
return count;
}
}