Leetcode刷题100-45. 跳跃游戏 II (C++详细解法!!!)

Come from : [https://leetcode-cn.com/problems/jump-game-ii/]

1.Question

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.

2.Answer

hard 类型题目(第一次 解决hard 类型 题目啊,好激动,好紧张)。贪心算法。
算法分析
在这里插入图片描述
AC代码如下:

class Solution {
public:
    int jump(vector<int>& nums) {
    	int len = nums.size();
        if(len  < 2)  //数组长度小于2,说明不用跳
        {
            return 0;
        }
        
        int jump_min = 1;  //能进行到这说明 至少跳一次
        int current_max_index = nums[0]; //当前可以达到的最远位置
        int pre_max_index = nums[0];  //在遍历过程中,可以达到的最远位置
        
        for(int i = 1; i < len ; ++i)
        {
            if( i > current_max_index )  //无法向前移动了,才进行跳跃(贪心思想算法)
            {
                ++jump_min;
                current_max_index = pre_max_index; //更新当前可以到达的最远位置
            }
            if(pre_max_index < nums[i] + i)
            {
                pre_max_index = nums[i] + i;//更新premax_max_index,即最远位置;
            }
        }
        return jump_min;
    }
};

3.大神的算法

大神AC速度第一代码:

class Solution {
public:
    int jump(vector<int>& nums) {
        int step = 0;
        for (int i = 0, j = 0, k = 0; i < nums.size() - 1; i++) {
            j = max(i + nums[i], j);
            if (i >= k) {
                k = j;
                step++;
            }
        }
        return step;
    }
};

4.我的收获

贪心算法进阶啦。。。
fighting。。。

2019/6/12 胡云层 于南京 100

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值