larscheng / algo

0 stars 0 forks source link

【Check 77】2024-05-18 - 55. 跳跃游戏 #183

Open larscheng opened 4 months ago

larscheng commented 4 months ago

55. 跳跃游戏

larscheng commented 4 months ago

思路

动态规划1

动态规划2

    public boolean canJump(int[] nums) {
        if (nums.length > 1 && nums[0] == 0) {
            return false;
        }
        int[] dp = new int[nums.length];
        dp[0] = nums[0];
        for (int i = 1; i < nums.length; i++) {
            dp[i] = Math.max(dp[i - 1], i + nums[i]);
            if (dp[i] >= nums.length - 1) {
                return true;
            }
            if (dp[i] == i) {
                return false;
            }
        }
        return true;
    }
larscheng commented 4 months ago

思路

记录每个节点可以跳到的最远位置 遍历的过程中如果当前位置大于历史最远位置,说明无法跳到该位置,否则说明可以跳完所有位置 O(n)/O(1)

代码

class Solution {

    public boolean canJump(int[] nums) {
        int k = 0;
        for (int i = 0; i < nums.length; i++) {
            if (i > k) {
                return false;
            }
            k = Math.max(k, i + nums[i]);
        }
        return true;
    }
}