每日一题:55. 跳跃游戏

78 阅读1分钟

package com.ljp.test.leetcode;

/**

  • 55. 跳跃游戏

  • 给定一个非负整数数组nums ,你最初位于数组的第一个下标 。

  • 数组中的每个元素代表你在该位置可以跳跃的最大长度。

  • 判断你是否能够到达最后一个下标。

  • 示例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

  • 来源:力扣(LeetCode)

  • 链接:55. 跳跃游戏

  • 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

  • @author luojunping

  • @since 2023-03-08 */ public class Number0055 {

    public static void main(String[] args) { int[] nums1 = {2, 3, 1, 1, 4}; int[] nums2 = {3, 2, 1, 0, 4}; System.out.println(DynamicPlanning.jumpToLast(nums1)); System.out.println(DynamicPlanning.jumpToLast(nums2)); System.out.println("-------------------------------"); System.out.println(Greedy.jumpToLast(nums1)); System.out.println(Greedy.jumpToLast(nums2)); }

    /**

    • 动态规划 */ private static class DynamicPlanning {

      public static boolean jumpToLast(int[] nums) { int length = nums.length; boolean[] dp = new boolean[length]; dp[0] = true; for (int i = 1; i < length; i++) { dp[i] = false; } for (int i = 1; i < length; i++) { for (int j = 0; j < i; j++) { if (dp[j] && j + nums[j] >= i) { dp[i] = true; break; } } } return dp[length - 1]; }

    }

    /**

    • 贪心算法 */ private static class Greedy {

      public static boolean jumpToLast(int[] nums) { int arriveLastIndex = 0, length = nums.length; for (int i = 0; i < length; i++) { if (i <= arriveLastIndex) { arriveLastIndex = Math.max(arriveLastIndex, i + nums[i]); if (arriveLastIndex >= length - 1) { return true; } } else { return false; } } return false; }

    }

}