leetcode【每日一题】跳跃游戏Java

题干

给定一个非负整数数组,你最初位于数组的第一个位置。

数组中的每个元素代表你在该位置可以跳跃的最大长度。

判断你是否能够到达最后一个位置。

示例 1:

输入: [2,3,1,1,4]
输出: true
解释: 我们可以先跳 1 步,从位置 0 到达 位置 1, 然后再从位置 13 步到达最后一个位置


示例 2:

输入: [3,2,1,0,4]
输出: false
解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。

想法

从前向后遍历 维护能够到达的最远距离
只要这个最远距离大于等于最后一个数的位置即可
注意遍历的时候只有先到达现在的位置才可以更新最远距离
也就是之前的最远距离要大于现在的index

Java代码

package daily;

public class CanJump {
    public boolean canJump(int[] nums) {
     int len=nums.length;
     //右边能到的最远距离
     int right=0;
     for(int i=0;i<len;i++ ){
         //现在i这个位置必须可以到达
         if (i<=right){
             right=Math.max(right,i+nums[i]);
         }
         //最远距离超过最右的点即可
         if(right>=len-1){
             return  true;
         }
     }
     return  false;
    }
    public  static  void main(String args[]){
        CanJump canJump=new CanJump();
        int [] test1={2,3,1,1,4};
        int [] test2={3,2,1,0,4};
        System.out.println(canJump.canJump(test1));
        System.out.println(canJump.canJump(test2));
    }
}

更快的 逆向思考的代码

class Solution {
    public boolean canJump(int[] nums) {
        int max = 0;
        int last = nums.length - 1;
        for (int i = nums.length - 1; i >= 0; i--) {
            if (nums[i] + i >= last) {
                last = i;
            }
        }
        return last == 0;
    }
}

我的leetcode代码都已经上传到我的git

发布了180 篇原创文章 · 获赞 0 · 访问量 3759

猜你喜欢

转载自blog.csdn.net/qq_43491066/article/details/105575543