[LeetCode] 55. 跳跃游戏

题目链接 : https://leetcode-cn.com/problems/jump-game/

题目描述:

给定一个非负整数数组,你最初位于数组的第一个位置。

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

判断你是否能够到达最后一个位置。

示例:

示例 1:

输入: [2,3,1,1,4]
输出: true
解释: 从位置 0 到 1 跳 1 步, 然后跳 3 步到达最后一个位置。

示例 2:

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

思路:

贪心算法

思路一:

从前往后跳

思路二:

从后往前推


45. 跳跃游戏 II一样的,

[解题链接](45. 跳跃游戏 II)


关注我的知乎专栏,了解更多解题技巧,大家共同进步!

代码:

思路一:

python

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        start = 0
        end = 0
        n = len(nums)
        while start <= end and end < len(nums) - 1:
            end = max(end, nums[start] + start)
            start += 1
        return end >= n - 1

java

class Solution {
    public boolean canJump(int[] nums) {
        int start = 0;
        int end = 0;
        while (start <= end && end < nums.length - 1) {
            end = Math.max(end, nums[start] + start);
            start++;
        }
        return end >= nums.length-1;
    }
}

思路二

python

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        #start = 0
        n = len(nums)
        start = n - 2
        end = n - 1
        while start >= 0:
            if start + nums[start] >= end: end = start
            start -= 1
        return end <= 0

java

class Solution {
    public boolean canJump(int[] nums) {
        int n = nums.length;
        int start = n - 2;
        int end = n - 1;
        while (start >= 0) {
            if (start + nums[start] >= end) end = start;
            start--;
        }
        return end <= 0;
    }
}
原文地址:https://www.cnblogs.com/powercai/p/10895320.html