0
点赞
收藏
分享

微信扫一扫

Day33 跳跃游戏

给定一个非负整数数组 nums ,你最初位于数组的 第一个下标 。数组中的每个元素代表你在该位置可以跳跃的最大长度。判断你是否能够到达最后一个下标

https://leetcode-cn.com/problems/jump-game/

示例1:

示例2:

提示:

Java解法

package sj.shimmer.algorithm.m2;

/**
 * Created by SJ on 2021/2/26.
 */

class D33 {
    public static void main(String[] args) {
        System.out.println(canJump(new int[]{2, 3, 1, 1, 4}));
        System.out.println(canJump(new int[]{3, 2, 1, 0, 4}));
        System.out.println(canJump(new int[]{2,0}));
        System.out.println(canJump(new int[]{8,2,4,4,4,9,5,2,5,8,8,0,8,6,9,1,1,6,3,5,1,2,6,6,0,4,8,6,0,3,2,8,7,6,5,1,7,0,3,4,8,3,5,9,0,4,0,1,0,5,9,2,0,7,0,2,1,0,8,2,5,1,2,3,9,7,4,7,0,0,1,8,5,6,7,5,1,9,9,3,5,0,7,5}));
    }

    public static boolean canJump(int[] nums) {
        if (nums != null) {
            int length = nums.length;
            int maxIndex = 0;
            for (int i = 0; i < length; i++) {
                if (i<=maxIndex) {//可达
                    maxIndex = Math.max(maxIndex, i + nums[i]);
                    if (maxIndex>=length-1) {
                        return true;
                    }
                }else {
                    return false;
                }
            }
        }
        return false;
    }

}

官方解

https://leetcode-cn.com/problems/jump-game/solution/tiao-yue-you-xi-by-leetcode-solution/

  1. 贪心算法

    • 时间复杂度:O(n)
    • 空间复杂度:O(1)
举报

相关推荐

0 条评论