• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ArgenBarbie
博客园    首页    新随笔    联系   管理    订阅  订阅
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;
}

 

posted on 2016-03-09 22:57  ArgenBarbie  阅读(297)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3