题目
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.)
Note:
You can assume that you can always reach the last index.
跳到最后一个元素所需最少次数
思路
在算法中要记录当前一跳所能到达的最远距离、上一跳所能到达的最远距离,和当前所使用跳数就可以了。另外需要注意的一点是:题意要求不一定非得跳到last index,越过去也算,这点需要特别强调。
代码
class Solution {
public:
int jump(vector<int>& nums) {
int ret = 0;//当前跳数
int last = 0;//上一跳可达最远距离
int cur = 0;//当前一跳可达最远距
for (int i = 0; i < nums.size(); ++i) {
//需要进行下次跳跃,则更新last和当执行的跳数ret
if (i > last) {
last = cur;
++ret;
}
//记录当前可达的最远点
cur = max(cur, i+nums[i]);
}
return ret;
}
};