美文网首页
Jump Game问题

Jump Game问题

作者: juexin | 来源:发表于2017-02-17 17:04 被阅读0次

    Jump Game I
    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.

    class Solution {
    public:
        bool canJump(vector<int>& nums) {
            int reach = 0;
            
            for(int i=0;i<=reach;i++)  //特别注意这个reach
            {
                reach = max(reach,nums[i]+i);
                if(reach>=nums.size()-1)
                  return true;
            }
            return false;
        }
    };
    

    **Jump Game II **
    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.)
    Note:
    You can assume that you can always reach the last index.

    class Solution {
    public:
        int jump(vector<int>& nums) {
            int rec = 0;
            int curRch = 0;
            int curMax = 0;
            for(int i=0;i<nums.size();i++)
            {
                if(curRch<i)  //特别注意这个判断条件
                {
                    rec++;
                    curRch = curMax;
                }
                curMax = max(curMax,nums[i]+i);
            }
            return rec;
        }
    };
    

    相关文章

      网友评论

          本文标题:Jump Game问题

          本文链接:https://www.haomeiwen.com/subject/sxjlwttx.html