现在的位置: 首页 > 综合 > 正文

Jump Game — leetcode

2018年10月18日 ⁄ 综合 ⁄ 共 844字 ⁄ 字号 评论关闭

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.

For example:

A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

算法

思路:从后往前推,

为了跳到结尾,

每往前倒推一步,累加步数,并看看当前位置的值是否大于该步数。

如果该值大于需求步数,则表示从该位置可以跳到结尾。

则此位置可以视作新的结尾。将问题缩减为,看是否能跳到此新结尾。

此算法在leetcode上实际执行时间为18ms。

class Solution {
public:
    bool canJump(int A[], int n) {
        int step = 0;
        for (int i=n-1; i>=0; i--, step++)
                if (A[i] >= step)
                        step = 0;

        return !--step;
    }
};

下面两则算法摘自leetcode:

算法二:

 从后往前推       本算法来源

记录下,能跳到结尾的最小位置。

如果当前位置,能够跳到最小位置。则当前位置成为新的最小位置。

bool canJump(int A[], int n) {
    int last=n-1,i,j;
    for(i=n-2;i>=0;i--){
        if(i+A[i]>=last)last=i;
    }
    return last<=0;
}

算法三:

从前往后,看能到达的最远距离。

此算法在leetcode上实际执行时间为17ms。
本算法来源

bool canJump(int A[], int n) {
    int i = 0;
    for (int reach = 0; i < n && i <= reach; ++i)
        reach = max(i + A[i], reach);
    return i == n;
}

抱歉!评论已关闭.