首页 > 代码库 > LeetCode:Jump Game

LeetCode:Jump Game

题目描述:

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.


思路分析:遍历数组。在遍历的过程中,计算已遍历了的所有点能到达的最远距离。当遇到值为0的元素时,比较当前能达到的最远距离与当前遍历元素的下标的大小。如果当前能达到的最远距离大,则表示能跳过这个值为0的元素,否则就表示不能越过这个元素,即这个元素即为能跳到的最远的元素。


代码:

bool Solution::canJump(int A[], int n)
{
    int pos = 0;
    int farest = 0;
    int i;
    for(i = 0;i < n;i++)
    {
        if(A[i] != 0)
            farest = farest > (i+A[i]) ? farest : (i+A[i]);
        else
        {
            if(farest > i)
                continue;
            else
                break;
        }
    }

    return farest >= n-1;
}


LeetCode:Jump Game