Day33 跳跃游戏

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

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

示例1:

输入:nums = [2,3,1,1,4]
输出:true
解释:可以先跳 1 步,从下标 0 到达下标 1, 然后再从下标 1 跳 3 步到达最后一个下标。

示例2:

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

提示:

1 <= nums.length <= 3 * 104
0 <= nums[i] <= 105

Java解法

思路:

  • 考虑用回溯处理,能够算出,但重复操作太大,计算超时

    public static boolean canJump(int[] nums) {
        ArrayList<Boolean> possibles = new ArrayList<>();
        backTry(possibles,nums,0);
        return !possibles.isEmpty();
    }
    
    public static void backTry(List<Boolean> possibles, int[] nums, int index) {
        int length = nums.length;
        if (index == length-1) {
            possibles.add(true);
            return;
        }
        int num = nums[index];
        if (num==0) {
            return;
        }
        int i =1;
        while (i< num+1&&index+i<length) {
            backTry(possibles,nums,index+i);
            i++;
        }
    }
    
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)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值