您的位置:首页 > 其它

【Leetcode】45. Jump Game II 跳跃游戏 II

2019-01-23 18:58 375 查看

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.

解法

参考评论区@tonyfirst1解法

[l,r)
是需要至少
ans
次跳跃才能到达的地方:

  1. r>=n
    时,已经跳到终点了,输出
    ans
  2. 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: