代码随想录 Leetcode45. 跳跃游戏 II-代码(首刷看解析 2024年2月15日):

时间:2024-02-18 21:50:56
class Solution {
public:
    int jump(vector<int>& nums) {
        if (nums.size() == 1) return 0;
        int res = 0;
        int curDistance = 0;
        int nextDistance = 0;
        for (int i = 0; i < nums.size(); ++i) {
            nextDistance = max(i + nums[i], nextDistance);
            if (i == curDistance) {
                res++;
                curDistance = nextDistance;
                if (nextDistance >= nums.size() - 1) break;
            }
        }
        return res;
    }
};