Killing LeetCode [55] 跳跃游戏

Description

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

Intro

Ref Link:https://leetcode.cn/problems/jump-game/
Difficulty:Medium
Tag:Array、Dynamic Programming
Updated Date:2023-07-15

Test Cases

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

思路

  • 动态规划

Code AC

class Solution {
	public boolean canJump(int[] nums) {
        // Space Complexity Optimization  O(n) -> O(1)
        int maxJumpIndex = nums[0];
        for (int i = 1; i < nums.length; i++) {
            if (i > maxJumpIndex) return false;  // can not reach here anymore
            maxJumpIndex = Math.max(maxJumpIndex, i + nums[i]);
        }
        return maxJumpIndex >= nums.length - 1 ? true : false;
    }
    
    public boolean canJump1(int[] nums) {
        // define dp[i] can jump max distince index value when at index i
        int[] dp = new int[nums.length];
        dp[0] = nums[0];
        for (int i = 1; i < nums.length; i++) {
            if (i > dp[i-1]) return false;  // can not reach here anymore
            dp[i] = Math.max(dp[i-1], i + nums[i]);
        }
        return dp[nums.length - 1] >= nums.length - 1 ? true : false;
    }

    public boolean canJump(int[] nums) {
        if(nums == null | nums.length == 0) return false;
        boolean[] f = new boolean[nums.length];
        f[0] = true;

        for(int i=1; i<nums.length; i++){
            for(int j=0; j<i; j++){
                if(f[j] && nums[j]+j>=i){
                    f[i] = true;
                    break;
                }
            }
        }
        return f[nums.length-1];
    }
}

Accepted

172/172 cases passed (2 ms)
Your runtime beats 91.57 % of java submissions
Your memory usage beats 65.84 % of java submissions (42.4 MB)

复杂度分析

  • 时间复杂度:O(n)
  • 空间复杂度:O(1)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值