zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    POJ1422 最小路径覆盖
    POJ1422 最小路径覆盖
    POJ1125 Floyd
    POJ1125 Floyd
    POJ2570 二进制,位运算,Floyd
    POJ2570 二进制,位运算,Floyd
    POJ2446 二分匹配
    POJ2536 二分图匹配
    POJ2536 二分图匹配
    POJ3692 最大点权独立集元素个数
  • 原文地址:https://www.cnblogs.com/argenbarbie/p/5260135.html
Copyright © 2011-2022 走看看