1.题目描述

45. 跳跃游戏 II

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

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

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

示例:

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

说明:

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

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package swu.xl.algorithm.code_04_07.experiment_4;

public class Solution {
/**
* leetcode 跳跃游戏 II
* @param nums
* @return
*/
public static int jump(int[] nums) {
//记录当前能够跳跃的最大距离
int current_most_large = 0;
//记录跳跃的边界
int current_jump_end = 0;
//记录跳跃的步数
int step = 0;

//因为第一次已经跳跃,所以最后一次nums.lemgth-1不用枚举了
for (int i = 0; i < nums.length - 1; i++) {
//刷新当前能够跳跃的最大距离
//新位置能够跳跃的最大距离:i+nums[i]
//是指自上一次的边界后能跳跃的最大距离
current_most_large = Math.max(current_most_large,i+nums[i]);

//是否是第一次跳或者跳到了边界(到了边界就要跳跃了)
if (i == current_jump_end){
//跳跃
step++;

//更新边界
//边界一定大于当前的位置 i
//不然就永远跳不出去
//也就不符合题目的 总是可以到达数组的最后一个位置。
current_jump_end = current_most_large;
}
}

return step;
}

/**
* 测试程序
* @param args
*/
public static void main(String[] args) {
int[] nums = new int[]{2,3,1,1,4};

System.out.println(jump(nums));
}
}

代码思路:

  • 贪婪算法,我们每次在可跳范围内选择可以使得跳的更远的位置。
  • 这里要注意一个细节,就是 for 循环中,i < nums.length - 1,少了末尾。因为开始的时候边界是第 0 个位置,steps 已经加 1 了。如果最后一步刚好跳到了末尾,此时 steps 其实不用加 1 了。如果是 i < nums.length,i 遍历到最后的时候,会进入 if 语句中,steps 会多加 1。