问题:
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.)
首先算出从第一个index可以跳的最远距离,保存为farest。然后在从1到farest之间找到一个能跳到的new farrest,并increment step。
代码:
class Solution{
public:
int jump(int A[], int n) {
if (n == 1) return 0;
int step = 1;
int i = 0;
int farest = i + A[i];
i ++;
while (i < n) {
if (farest >= n - 1)
return step;
int new_farest = farest;
for (; i <= farest; i ++) {
new_farest = std::max(new_farest, A[i] + i);
}
step ++;
farest = new_farest;
}
return step;
}
};