55. 45. Jump Game II *HARD*

Posted ArgenBarbie

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了55. 45. Jump Game II *HARD*相关的知识,希望对你有一定的参考价值。

1.

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.

bool canJump(vector<int>& nums) {
    int n = nums.size();
    if(n <= 1)
        return true;
    int coverPos = 0, maxPos = -1, t, next, i, j, k = 0;
    for(i = 0; i < n && i <= coverPos; i++)
    {
        t = nums[i] + i;
        if(t > coverPos)
            coverPos = t;
        if(coverPos >= n-1)
            return true;
    }
    return false;
}

 

 

2.

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.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

int jump(vector<int>& nums) {
    int n = nums.size();
    if(n <= 1)
        return 0;
    int coverPos = 0, maxPos = -1, t, next, i, j, k = 0;
    for(i = 0; i < n && i <= coverPos;)
    {
        t = i + nums[i];
        if(t > coverPos)
        {
            coverPos = t;
            k++;
        }
        if(coverPos >= n-1)
            break;
        for(j = i+1; j <= coverPos; j++)
        {
            t = j + nums[j];
            if(t > maxPos)
            {
                maxPos = t;
                next = j;
            }
        }
        i = next;
    }
    return k;
}

 

以上是关于55. 45. Jump Game II *HARD*的主要内容,如果未能解决你的问题,请参考以下文章

45. Jump Game II

45. Jump Game II

45. Jump Game II

45. Jump Game II

45. Jump Game II

45. Jump Game II