45. 跳跃游戏 II

class Solution {
public:
    int jump(vector<int>& nums) {
        int len = nums.size();
        int start=0,end=1,ans=0;
        while(end<len){
            int maxPos=0;
            for(int i=0;i<end;++i){
                maxPos = max(maxPos,i+nums[i]);
            }
            start=end;
            end=maxPos+1;
            ans++;
        }
        return ans;
    }
};

优化i后

class Solution {
public:
    int jump(vector<int>& nums) {
        int maxPos = 0, n = nums.size(), end = 0, step = 0;
        for (int i = 0; i < n - 1; ++i) {
            if (maxPos >= i) {
                maxPos = max(maxPos, i + nums[i]);
                if (i == end) {
                    end = maxPos;
                    ++step;
                }
            }
        }
        return step;
    }
};

你可能感兴趣的:(LeetCode,游戏,算法,leetcode)