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.
使用贪心,只不过是要记录当前一跳所能到达的最远距离、上一跳所能达到的最远距离,和当前所使用跳数就可以了,代码如下:
class Solution {
public:
int jump(vector<int>& nums) {
int n = nums.size();
int ret = 0;//当前跳数
int last = 0;//上一跳可达最远距离
int curr = 0;//当前一跳可达最远距
for (int i = 0; i < n; ++i) {
//无法向前继跳直接返回
if(i>curr){
return -1;
}
//需要进行下次跳跃,则更新last和当执行的跳数ret
if (i > last) {
last = curr;
++ret;
}
//记录当前可达的最远点
curr = max(curr, i+nums[i]);
}
return ret;
}
};