1.题目描述
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.
2. 代码
分析:本题的贪心策略是每次向前跳的时候都选择下一个最大跳距的结点,比如, 2,3,1,1,4 中,在 nums[0] 应该选择下一个 nums[1]==3 而不是直接跳到 nums[2]==1 ,因为 nums[1]>nums[2] 。
重点:为跳步计数,每一次能跳的最远距离是下标 curMaxReach ,如果 i 达到curMaxReach ,说明跳了一次(思考为什么?)。对于第一步来说,可以存在跳一次就达到终点的情况,所以起始计数 count=1 ;计数 count 不是到达下一个最远结点才开始计数,而是从当前最远结点出发开始下一跳就计数(因为下一跳可能超出范围!)。因此在第一跳的时候,初始最远距离当然是首个结点所能达到的 nums[0] ,当 i 达到nums[0] 时,就开始了下一跳(一定会做出下一跳,除非超过终点),因此计数加一, count==2 而不是 count==1 ,(思考为什么?)。因为此时开始是第二跳了
希望以上通俗的解释能对某些朋友有帮助。
class Solution {
public:
int jump(vector<int>& nums) {
if(nums.size() <= 1) return 0;
int curMaxReach = nums[0], maxReachPos = nums[0];
int i = 1, count = 1;
for(; i < nums.size() && i <= maxReachPos; ++i) {
curMaxReach = max(curMaxReach, i + nums[i]);
if(i == nums.size()-1) return count;
if(i == maxReachPos) {
count++;
maxReachPos = curMaxReach;
}
}
return count;
}
};
联系邮箱:sysuygm@163.com