leetcode 每日一题 45. 跳跃游戏 II

贪心算法

思路:

从头开始遍历数组,用end记录当前步所能到达的截止位置,maxPos记录下一步所能到达的最大位置,当遍历到当前步截止位置时,步数加一,end更新为下一步所能到达的最大位置,继续遍历。

代码:

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

猜你喜欢

转载自www.cnblogs.com/nilhxzcode/p/12971311.html
今日推荐