Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

55.跳跃游戏 #11

Open
wtfjun opened this issue Oct 18, 2018 · 0 comments
Open

55.跳跃游戏 #11

wtfjun opened this issue Oct 18, 2018 · 0 comments

Comments

@wtfjun
Copy link
Owner

wtfjun commented Oct 18, 2018

leetcode 55. 跳跃游戏

题目描述

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

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

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

示例 1:

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

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

解题思路:

数组的每一个位置记录了当前路程和它能跳到的最远路程,我们只要找到这个位置,并根据这个位置不断寻找下一个位置

若能走完数组,true

根据以上算法走不完,false

符合动态规划,算法复杂度为O(n)

代码如下

var canJump = function(nums) {
    let jumpStep = 1;
    let i = 0;
    for(; i < nums.length; i++) {
        let next = 0;
        let max = 0;
        for (let j = 0; j < jumpStep; j++) {
            if (i + j + nums[i + j] > max) {
                next = i + j;
                max = i + j + nums[i + j];
            }
        }
        i = next;
        console.log(i);
        jumpStep = nums[i];
        if (jumpStep === 0) break;
    }
    if (i < nums.length - 1) {
        console.log(false)
        return false;
    }
    console.log(true)
    return true;
};
@wtfjun wtfjun mentioned this issue Nov 2, 2018
@wtfjun wtfjun changed the title 55.跳跃游戏 55.跳跃游戏【中等】 Nov 13, 2018
@wtfjun wtfjun changed the title 55.跳跃游戏【中等】 55.跳跃游戏 Nov 13, 2018
@wtfjun wtfjun added the 中等 label Nov 13, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant