Jump Game & Jump Game II

方法:使用一个变量记录能到达的最远距离

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

 Jump Game II

class Solution {
public:
    int jump(vector<int>& nums) {
        int last = 0, cur = 0, result = 0;
        
        for(int i=0; i<nums.size(); ++i)
        {
            if(i > last)
            {
                last = cur;
                ++result;
            }
            
            cur = max(cur, i + nums[i]);
        }
        
        return result;
    }
};

 

posted @ 2017-06-10 20:00  chengcy  Views(136)  Comments(0Edit  收藏  举报