天天看点

Leetcode——55. Jump Game

题目原址

解题思路

给定一个数组,数组的下标表示你当前所在的位置,数组中的元素值表示你一次可以最大跳跃的步数,现在假设你在0位置上,判断是否可以跳到最末尾的位置。

使用贪心算法解决该题。使用两个指针

temp

maxReach

temp

用来表示当前位置,

maxReach

用来表示下一步能够到达的最远位置。在每次的遍历中都更新

maxReach

的值,以确保

maxReach

的值为每次遍历的最大值。直到遍历到数组末尾。这里面如果

maxReach

的值超过了数组的长度就说明能够到达数组的末尾。

AC代码

class JumpGame {
    public boolean canJump(int[] nums) {
        int maxReach = ;
        int temp = ;
        while(temp <= maxReach && temp < nums.length) {
            maxReach = Math.max(maxReach, temp + nums[temp]);
            temp ++;
        }

        return maxReach >= nums.length - ;
    }
}