LeetCode

    科技2025-02-09  13

    //思路就是:如果当前下标和它对应的数值的和要比数组最后一个数据的下标要大,那么就能到达最远的地方 package number5; //给定一个非负整数数组,你最初位于数组的第一个位置。 //数组中的每个元素代表你在该位置可以跳跃的最大长度。 //判断你是否能够到达最后一个位置。 //示例 1: //输入: [2,3,1,1,4] //输出: true //解释: 我们可以先跳 1 步,从位置 0 到达 位置 1, 然后再从位置 1 跳 3 步到达最后一个位置。 //示例 2: //输入: [3,2,1,0,4] //输出: false //解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。 public class Solution2 { public static void main(String[] args) { int[] nums= {0,2,3}; System.out.println(canJump(nums)); } public static boolean canJump(int[] nums) { int x=0; int max=x+nums[x];//代表当前能到达的最远位置 for (x =0; x <= max; x++) { if(max>=nums.length-1) return true; else if(max<x+nums[x]) max=x+nums[x]; } return false; } }
    Processed: 0.012, SQL: 8