友情支持
如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜
有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。
公众号的微信号是: jikerizhi 。因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。 |
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 <= nums.length <= 104
-
0 <= nums[i] <= 1000
-
题目保证可以到达
nums[n-1]
思路分析

-
一刷
-
二刷
-
二刷(优化)
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
/**
* Runtime: 1 ms, faster than 99.98% of Java online submissions for Jump Game II.
*
* Memory Usage: 36.4 MB, less than 100.00% of Java online submissions for Jump Game II.
*
* @author D瓜哥 · https://www.diguage.com
* @since 2019-10-26 11:29
*/
public int jump(int[] nums) {
if (Objects.isNull(nums) || nums.length == 0) {
return 0;
}
int step = 0;
int currentStepEnd = 0;
int currentFarthestIndex = 0;
for (int i = 0; i < nums.length - 1; i++) {
currentFarthestIndex = Math.max(currentFarthestIndex, i + nums[i]);
if (i == currentStepEnd) {
step++;
currentStepEnd = currentFarthestIndex;
}
}
return step;
}
// TODO: Dynamic Programming
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* @author D瓜哥 · https://www.diguage.com
* @since 2025-05-17 21:14:27
*/
public int jump(int[] nums) {
int length = nums.length;
int[] dp = new int[length];
Arrays.fill(dp, length + 1);
dp[0] = 0;
for (int i = 0; i < length; i++) {
int min = Math.min(length - 1, i + nums[i]);
for (int j = i + 1; j <= min; j++) {
dp[j] = Math.min(dp[j], dp[i] + 1);
}
}
return dp[length - 1];
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* @author D瓜哥 · https://www.diguage.com
* @since 2025-05-17 21:14:27
*/
public int jump(int[] nums) {
int length = nums.length;
int max = 0;
int step = 0;
int end = 0;
for (int i = 0; i < length; i++) {
max = Math.max(max, i + nums[i]);
if (max >= length - 1) {
return step + 1;
}
if (i == end) {
end = max;
step++;
}
}
return step;
}