Jump Game I,II

    xiaoxiao2021-03-25  119

    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.

    问题描述:一个非负数组中的每一个元素代表,从该位置可前进的最大格数,判断是否可以达到数组最后一个元素。

    采用的思想和Maximum Subarray的思想 reach表示目前所能到达的最远位置 nums[i]+i表述从i位置所能到达的最远位置

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

    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.

    问题描述:在JUMP GAME I的基础上,保证一定可以到达数组最后的一个元素,求最少需要的步数。

    采用的思想和之前类似,step表示步数,cur_distmax表示经过step后所能到达的最远距离,sum_distmax表示在step-1步内能够到达的最远距离。

    class Solution { public: int jump(vector<int>& nums) { int step=0; int cur_distmax=0; int sum_distmax=0; int n=nums.size(); for(int i=0;i<n;i++){ if(cur_distmax<i){ step++; if(cur_distmax<sum_distmax) cur_distmax=sum_distmax; } if(sum_distmax<nums[i]+i) sum_distmax=nums[i]+i; } return step; } };
    转载请注明原文地址: https://ju.6miu.com/read-3638.html

    最新回复(0)