【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.
解法
[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
相关文章推荐
- Leetcode 45. 跳跃游戏 II
- Leetcode 45. 跳跃游戏 II
- Leetcode做题日记:45. 跳跃游戏 II(PYTHON)
- [Leetcode] jump game ii 跳跃游戏
- leetcode解题之45. Jump Game II&55. Jump Game java (跳跃游戏)
- [LeetCode] 45. Jump Game II 跳跃游戏 II
- [LeetCode] Jump Game II 跳跃游戏之二
- leetcode。45. 跳跃游戏 II
- 【leetcode】Jump Game I, II 跳跃游戏一和二
- 【LeetCode】Jump Game II 跳跃游戏II - 贪心 Medium
- leetcode45.跳跃游戏 II
- leetcode45.跳跃游戏 II
- LeetCode-Jump Game II-跳跃游戏-BFS
- LeetCode | Jump Game II(跳跃游戏II)
- Leetcode 55. 跳跃游戏
- 45. Jump Game II(跳跃游戏II)
- leetCode 45.Jump Game II (跳跃游戏) 解题思路和方法
- 不一样的猜数字游戏 — leetcode 375. Guess Number Higher or Lower II
- lintcode-117-跳跃游戏 II
- leetcode 55. Jump Game 跳跃游戏 + 贪心算法