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.)
这道题的思路和I差不多,只是需要维护一个step来记录长度,也就是说只有超过了上次跳跃的最大长度,step才会增加。
代码如下
public static int jump(int[] A) {
if (A == null || A.length == 0)
return 0;
int lastDestination = 0;
int destination = 0;
int step = 0;
for (int i = 0; i <= destination && i < A.length; i++) {
if (i > lastDestination) {
step++;
lastDestination = destination;
}
destination = Math.max(destination, A[i] + i);
}
if (destination < A.length - 1)
return 0;
return step;
}