leetcode45 跳跃游戏2——贪心 (C++/Python)

发布时间 2023-10-16 00:38:25作者: 夫琅禾费米线

题目描述:

给定一个长度为 n 的 0 索引整数数组 nums。初始位置为 nums[0]

每个元素 nums[i] 表示从索引 i 向前跳转的最大长度。换句话说,如果你在 nums[i] 处,你可以跳转到任意 nums[i + j] 处:

  • 0 <= j <= nums[i] 
  • i + j < n

返回到达 nums[n - 1] 的最小跳跃次数。生成的测试用例可以到达 nums[n - 1]

 

示例 1:

输入: nums = [2,3,1,1,4]
输出: 2
解释: 跳到最后一个位置的最小跳跃数是 2。
     从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。

示例 2:

输入: nums = [2,3,0,1,4]
输出: 2

 

提示:

  • 1 <= nums.length <= 10^4
  • 0 <= nums[i] <= 1000
  • 题目保证可以到达 nums[n-1]

 

解法解析:

int maxIndex 为所能到达最大下标 maxIndex=max(maxIndex , i + nums[i]),值得注意只有当maxindex>i 时才能更新值(但题目前提时能到达终点,所以无需顾虑)

当 maxIndex 在nums【i】处更新值,代表先跳到nums【i】再往后跳能到的地方更远,所以step+1(跳到nums[i]处)

C++

class Solution {
public:
    int jump(vector<int>& nums) {
        //fronm this index the farest we can get to -> maxIndex        int length = nums.size();
        int destination=0;
        int maxindex=0;
        int step=0;
        for(int i=0;i<length-1;i++) {
            if (maxindex>=i) {
                maxindex=max(maxindex,nums[i]+i);
                if(i==destination) {//maxindex 在此处有更新
                    destination=maxindex;
                    step++;
                }
            }
        }
        return step;

    }
};

python

class Solution:
    def jump(self, nums: List[int]) -> int:
        n=len(nums)
        maxIndex,destination,step=0,0,0
        for i in range (n-1) :
            if maxIndex >= i:
                maxIndex=max(maxIndex,i+nums[i])
                if i == destination:
                    destination=maxIndex
                    step+=1
        return step

  说起来我老是忘记python没有 ++ 和 --