LeetCode(55)-Jump Game

版权声明:XiangYida https://blog.csdn.net/qq_36781505/article/details/83834590

55. Jump Game

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.
Determine if you are able to reach the last index.
Example 1:
Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
jump length is 0, which makes it impossible to reach the last index.

嗯,昨天晚上看到的这个题,典型的贪心算法,一上来就有了思路,但是一运行,只通过了百分之八十,然后一直找错误,东改西改一直没通过,伤心死我了,今天想的时候不再去看错误的结果了,一行一行的研究自己写的代码,(反正大体思路是没错的,就看具体细节错哪儿了)

先说这个题的思路吧:

贪心算法的核心,找到每次的最优解,使结果最优

  • 只要我们能使最终跳到最远(最优结果),然后在判断是否能跳出去就可以了

  • 从第i点开始起跳,j为跳的步数,跳的值为1<=j<=nums[i],然后怎样跳才是每步的最优解呢?

    • 我们记跳到的地方的value=nums[i+j],那么每次只要能保证value+j最大就行了
    • 然后下次就从i+j的位置起跳这样就能保证结果最优。

嗯,剩下的细节就不用写了吧,好晚了。
代码如下:

public boolean canJump(int[] nums) {
        if(nums.length<=1)return true;
        for (int i = 0; i <nums.length-1;) {
            int j,max=0,value=0;
            for (j = 1; j <=nums[i]; j++) {
                int sum=nums[i+j]+j+i;
                if(sum>max){
                    max=sum;
                    value=j;
                }
                if((i+j)>nums.length-1||max>=nums.length-1)return true;
            }
            i+=value;
            if(nums[i]==0)return false;
        }
        return true;
    }

嗯,这张图也算给我改bug改了这么久的一个小小的安慰吧_

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_36781505/article/details/83834590