45. Jump Game II(贪心)

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值