leetcode 55. 跳跃游戏【贪心】

按顺序遍历数组,使用一个变量保存所遍历过的所有位置中能达到的最远位置,当数组下标大于所能达到的最远位置时,说明这个下标表示的位置不可达,即退出遍历并返回false;当最远位置大于等于最后一个元素的下标时,说明可达,返回true

class Solution {
    public boolean canJump(int[] nums) {
        int max = 0;
        for(int i=0; i<nums.length;i++){
            if(i>max)break;
            max = Math.max(max, i+nums[i]);
            if(max >= nums.length-1){
                return true;
            }
        }
        return false;
    }
}
发布了55 篇原创文章 · 获赞 0 · 访问量 758

猜你喜欢

转载自blog.csdn.net/er_ving/article/details/105581131
今日推荐