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.
Note:
You can assume that you can always reach the last index.
解法
[l,r)
是需要至少ans
次跳跃才能到达的地方:
r>=n
时,已经跳到终点了,输出ans
r<n
时,分析每个i in xrange(l,r)
,第ans+1
次跳跃能到达的最远下标为:farmost=max(i+nums[i] for i in xrange(l,r))
,那么至少需要ans+1
次跳跃才能到达的地方就是[r,farmost+1)
[l,r)
里的每个下标都可以通过ans
次跳跃到达,因为(1)第一次的时候满足条件(2)当[l,r)
满足条件时,假设farmost=i+nums[i]
,由于步数小于等于nums[i]
的地方都可以跳,所以[i,i+nums[i]]
都是可以到达的,而[r,i+nums[i]+1)
一定包含在[i,i+nums[i]]
里,所以一定可以到达。
class Solution(object):
def jump(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
l,r,ans = 0,1,0
n = len(nums)-1
while n>=r:
ans += 1
l,r = r, max(j+nums[j] for j in xrange(l,r))+1
return ans