(Greedy) leetcode 55. 45. Jump Game I II

题意:从数组的索引为0处出发,数组中存储的是当前索引处能跳跃的步数,如arr[0] = 2,表示从索引0可以到达索引1和2。问最后是否能到达最后的索引。

思路:用reach: 记录从当前位置能到达的最远的位置(从0开始计数)每次reach取能到达的最大值。

class Solution {
public:
    bool canJump(vector<int>& nums) {
        if(nums.size()<2)
            return true;
        int reach = 0;  //reach: 记录从当前位置能到达的最远的位置
        for(int i=0; i<=reach && i<nums.size(); ++i){
            reach = max(reach, i+nums[i]);
            if(reach >= nums.size()-1) //能到达队尾
                return true;
        }
        return false;
    }
};

题意:返回到达最后位置的最小步数。

class Solution {
public:
    int jump(vector<int>& nums) {
        if(nums.empty() || nums.size() <=1)
            return 0;
        //cur_max : 当前位置所能到达的最远位置,next_max: 下一步所能到达的最远位置
        int cur_max = 0, next_max = 0, step = 0, index = 0;
        while(index <= cur_max){
            
            while(index <= cur_max){
                //计算每一步中所能达到的最大位置
                next_max = max(next_max, index+nums[index]);
                index ++;
            }
            cur_max = next_max;
            step ++;
            if(cur_max >= nums.size()-1)
                return step;
        }
        return 0;
    }
};

猜你喜欢

转载自www.cnblogs.com/Bella2017/p/11234728.html