问题:
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A = [2,3,1,1,4]
The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
代码示例:
这个问题可以装换一下思考方向:
题目要求计算最短到达末尾的跳数,我们可以转换为计算一棵“树”的深度。
我们将每一跳可以达到的数,当作节点放在同一层。最后一个节点对应的深度,就是最短跳数了。
例如题目中的[2,3,1,1,4, 2, 6, 7],对应的“树”就是:
level 0: 2 (下一层下标最大为2)
level 1: 3, 1 (下一层下标最大为4)
level 2: 1, 1, 4 (下一层下标最大为8)
level 3: 2, 6, 7 (因此,3跳即可)
public class Solution {
public int jump(int[] nums) {
if (nums == null || nums.length <= 1) {
return 0;
}
int level = 0;
//保存上一层计算出的最大下标
//初始为0 + nums[0]
int prevMax = nums[0];
//记录本层计算出的下一次最大下标
int currMax = 0;
//System.out.println("level0 " + nums[0]);
int i = 1;
while(i < nums.length) {
++level;
//System.out.print("level" + level + ": ");
//prevMax限制处于一层数的数量
while (i< nums.length && i <= prevMax) {
if (i + nums[i] > currMax) {
//更新最大可达下标
currMax = i + nums[i];
}
//System.out.print(nums[i] + " ");
++i;
}
//System.out.println();
prevMax = currMax;
currMax = 0;
}
return level;
}
}