美文网首页
Jump Game(Medium)

Jump Game(Medium)

作者: 海生2018 | 来源:发表于2019-11-14 18:14 被阅读0次

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Determine if you are able to reach the last index.

Example 1:

Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2:

Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
             jump length is 0, which makes it impossible to reach the last index.

Solution

class Solution {
    private boolean find=false;
    public boolean canJump(int[] nums) { 
        /*
        if(nums==null) return false;
        
        int index=0;
        dfs(nums,index);
        return find;
        */
        if(nums==null) return false;
        /*
        int reach=0,n=nums.length;
        for(int i=0;i<=reach;i++){
            if(i+nums[i]>reach) reach=i+nums[i];
            if(reach>=n-1) return true;
        }
        */
        int lastPos = nums.length - 1;
        for (int i = nums.length - 1; i >= 0; i--) {
            if (i + nums[i] >= lastPos) {
                lastPos = i;
            }
        }
        return lastPos == 0;
        return false;
    }
    /*
    private void dfs(int[] nums,int i){
        
        if(find){
            return;
        }
        if(i>=nums.length){
            return;
        }
        if(i==nums.length-1){
            find=true;
            return;
        }
        for(int j=nums[i];j>0;j--){
            dfs(nums,i+j);
        }
        
    }
    */
}

时间O(n)
空间O(1)

我只能想到回溯法,如我所料,超时了。
贪心法是最优算法,从后往前看,如果它的值加上它的位置超过了最后一个位置,动态更新最后一个位置到当前位置,依次往前递推。最后判断最后一个位置是不是初始位置0就可以了

相关文章

  • Jump Game(Medium)

    Given an array of non-negative integers, you are initiall...

  • [LeetCode 55] Jump Game (medium)

    55 Jump Game (medium) Given an array of non-negative inte...

  • [LeetCode] 55. Jump Game (Medium

    原题 题目意思即 每一格代表你当前最多能再往后跳几次,从第一格开始,如果能跳到最后一格返回true,反之为fals...

  • Jump Game

    Jump Game 今天是一道有关贪婪算法的题目,来自LeetCode#55,难度为Medium,Acceptan...

  • [DP]45. Jump Game II

    前篇 55. Jump Game 45. Jump Game II 感谢Jason_Yuan大神优秀的解析:链接 ...

  • Custer Jump

    Custer Jump is a jumping game, you will love this game. T...

  • Jump Game

    这道题有点像大富翁呀,题意也很简单明确,就不解释了。我首先想到的就是用迭代遍历硬杠它。从最大值开始跳,每个位置都是...

  • Jump Game

    Jump Game 题目分析:找出能够到达的最远距离是否能到最后一个索引。我的想法是从第一个开始,不断更新最长到达...

  • Jump Game

    https://leetcode.com/problems/jump-game-ii/给定一个数组nums,数组内...

  • Jump Game

    版权声明:本文为博主原创文章,转载请注明出处。个人博客地址:https://yangyuanlin.club欢迎来...

网友评论

      本文标题:Jump Game(Medium)

      本文链接:https://www.haomeiwen.com/subject/ltfdictx.html