let 45 Jump Game II

本文介绍了一种解决跳跃游戏问题的贪心算法实现方法。该算法通过不断更新可达最远距离来计算最少跳跃次数。文章详细解释了算法的逻辑,并提供了一个具体的Java代码示例。

主题思想: 这是一道贪心算法, 要尽可能地跳的远,首先 明确什么时候更新步数, 根据当前i 能知道从i 能走到的最大步数 ith-long,在没走到ith-long达到的最大步数之前,记录中间步骤所能更新的最大值,当i达到ith-long 是更新下一步最大值为中间的最大值,并更新步数。

class Solution {
    public int jump(int[] nums) {


        if(nums==null||nums.length<2) return 0;
        int n=nums.length;
        int step=0,longestDistance=0,nextLongestDistance=0;

        // the nums[n-1] can be reached by [n-1] ....0 so, i from 0 to n-2
        for(int i=0;i<n-1;i++){

            //nextLongestDistance 是i到longestDistance 所能走到的最大步数
            nextLongestDistance=Math.max(nextLongestDistance,i+nums[i]);
       //当i达到最大步数时,更新step,
            if(i==longestDistance){
                longestDistance=nextLongestDistance;
                step++;
            }
        }
        return step;
    }
}
I bet all of you were once keen on the game Mario.Then,how was your game going at that time?As you know,pits are found everywhere in the Mario's world.You can not enjoy your triumph unless crossing all the pits without falling down.If you fail to make it,will you fake it? Suppose that there are n pits in the game,the width of which are W1、W1……Wn(unit:meter) .But the location of all the pits is uncertain. Mario can jump as far as m meters each time.What's more,he can choose every start point as he like.However,since walking is forbidden,he can only move through jumping. Could you tell me if Mario can pass the level? (If Mario stands at the edge of a pit,he will not fall down.) The input consists of multiple test cases.Each of them includes two lines.There are 2 numbers: m(Type:double,0<m<500) and n(Type:int,0<n<1000) in the first line.In the second line,n numbers whose type are double should be entered in,each of which presents the width(unit:meter) of the pit. Aiming at applying an optimal stratege ,Mario will take off at a certain point.In that case,if you are confident that Mario is capable of passing the game, your output will be "I'm a super gamer!".On the other hand,if you believe that Mario is bound to lose ,your output should be "Oh Damn!".In spite of the clear results,uncertainty also exists in the game.Therefore,if you are confused about Mario's fate,your output can be "Let me think again...". 输入样例 2.0 3 1.0 0.4 0.2 1.0 1 2.0 3.0 4 2.0 0.5 0.8 1.0 输出样例 I'm a super gamer! Oh Damn! Let me think again...
最新发布
12-24
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值