码迷,mamicode.com
首页 > 其他好文 > 详细

55. 45. Jump Game II *HARD*

时间:2016-03-09 23:44:44      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:

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*

标签:

原文地址:http://www.cnblogs.com/argenbarbie/p/5260135.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!