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.
Example:
Input: [2,3,1,1,4] Output: 2 Explanation: 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.
这道题就是给一个数组, 数组的每个元素代表了我在这个数组的当前位置后能够往下走的步数, 题目给出了一定能到达尾部的前提。 思路其实很简单, 拿Example举例, 我的初始位置处于0 那么我能继续往下走的位置就是arr[1] , arr[2], 那么我再计算出arr[1] arr[2]上给的数字能让我到达的最远的地方, 然后从arr[3]开始到这个最远的地方的区间当中又有一个位置可以让我在这之后又走到相较最远的地方, 然后每次这个区间就等于一次步数。 根据这个思路代码就很好写了.
class Solution {
public int jump(int[] A) {
int jumps = 0, curEnd = 0, curFarthest = 0;
for (int i = 0; i < A.length - 1; i++) {
// 当前区间能让我走的最远的地方
curFarthest = Math.max(curFarthest, i + A[i]);
// 上次区间标记的最远的地方 , 到了这个位置步数+1.并更新curEnd等于这次区间最远的地方
// 根据example的数据举个例子, 2是上次区间最远的地方, 4是当前区间最远的地方.
// 就因为arr[1]和arr[2]能让我走的最远的位置索引为4。
if (i == curEnd) {
jumps++;
curEnd = curFarthest;
}
}
return jumps;
}
}