045. Jump Game II
Question 45
(Jump Game II -> 055. Jump Game)
https://leetcode.com/problems/jump-game-ii/
Given an array of non-negative integers, you are initially positioned at the first index of the array.Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps.
Example:
Input: [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2.
Jump 1 step from index 0 to 1, then 3 steps to the last index.
Answer
以“位置”為判斷是否抵達標準, 可抵達之最後位置(end)超過 nums 的最後一位(總長度 - 1)
每次跳躍(step + 1),重新定義要檢查的 start, end start : 上次可跳躍範圍 + 1 end:本次跳躍可跳最遠的位置
class Solution:
def jump(self, nums: 'List[int]') -> 'int':
lennums = len(nums)
step, end, start, maxend = 0, 0, 0, 0
while end < lennums - 1 :
step += 1
maxend = end + 1
for i in range(start, end+1):
maxend = max( maxend, i + nums[i] )
end, start = maxend, end + 1
return step
Last updated