题目
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.
Note:
You can assume that you can always reach the last index.
思路
注意到,题目有这样一个性质:若我们走的步数记作step,可以到达某个位置,那么走到这个位置之前的位置最多不超过step步。
这启发我们采用下面的算法,从数组头开始往后扫描,记录在当前所走的步数下(记作step),所能走到的最远位置(记作end)。同时我们维护一个farthest变量,表示再走一步,点最远可以到达地方的下界。当扫描到end的时候,farthest变成下一步最远可到达的地方,此时更新step加一,end=farthest。当end已经达到或超过数组最后一个元素时,返回的step,即是到达数组最后位置需要跳动的最小步数。
代码
class Solution {
public:
int jump(vector<int>& nums) {
int step = 0;
int end = 0;
int farthest = 0;
for (int i = 0; i != nums.size(); ++i) {
if (end >= nums.size() - 1) {
break;
}
if (i + nums[i] > farthest) {
farthest = i + nums[i];
}
if (i == end) {
++step;
end = farthest;
}
}
return step;
}
};