HOT 100 › 索引 › B14 贪心算法 Greedy
LC 45跳跃游戏 IIJump Game II 中等
每次跳跃距离不超过该位置的数值,保证能到末尾,求到达末尾的最少跳跃次数。
思路 贪心按层扩展(层级 BFS):end 为当前层边界,mx 为层内最远,走到边界时步数加一并跳到 mx。时间 O(n)。
class Solution: def jump(self, nums: List[int]) -> int: ans = end = mx = 0 for i in range(len(nums) - 1): mx = max(mx, i + nums[i]) if i == end: end = mx ans += 1 return ans