Leetcode45. 跳跃游戏 II -hot100-代码随想录

目录

题目:

代码(首刷看解析 2024年2月15日):

代码(二刷自解 2024年3月9日 贪心 8min)

代码(三刷看解析 2024年6月11日 go)


题目:

Leetcode45. 跳跃游戏 II -hot100-代码随想录_第1张图片


代码(首刷看解析 2024年2月15日):

class Solution {
public:
    int jump(vector& 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;
    }
};

代码(二刷自解 2024年3月9日 贪心 8min)

class Solution {
public://贪心
    int jump(vector& nums) {
        int n = nums.size();
        // 遍历 当前位置i ~ 当前位置+nums[i],记录最大 max[i + nums[i]]作为下一个i
        int step = 0;
        int index = 0;
        while (index != n - 1) {
            int maxV = INT_MIN;
            int nextIndex = index;
            for (int i = index; i <= index + nums[index]; ++i) {
                if (i == n - 1) return step + 1;
                if (maxV < i + nums[i]) {
                    maxV = i + nums[i];
                    nextIndex = i;
                }
            }
            index = nextIndex;
            step++;
        }
        return step;
    }
};

代码(三刷看解析 2024年6月11日 go)

func jump(nums []int) int {
    jumpTimes := 0
    maxRange := 0
    nextMaxRange := 0
    for i := 0; i < len(nums) - 1; i++ {
        nextMaxRange = max(i + nums[i], nextMaxRange)
        if maxRange == i {
            jumpTimes++
            maxRange = nextMaxRange
        }
    }
    return jumpTimes
}

func max(a,b int) int {
    if a > b {
        return a
    }
    return b
}

你可能感兴趣的:(#,leetcode,---medium,算法)