LeetCode #45 Jump Game II

Question

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.

贪心 O(n)

这是一道贪心题,难就难在是一道贪心题。只要想通了,就好解决了。

贪心的对象不是当前能够达到最远的点,比如sample中[2,3,1,1,4]显然第一步显然不是1,而是3。当然也是不是数字大小。贪心对象应是当前所能达到范围中,能到的最远范围的点。比如第一个点为2,当前能到达3,1两点,3能够达到的范围比1大,所以是3。

其实是一个bfs的思想,用bfs的思想能很好证明。

具体实现有简洁的代码,本人第一次实现时相对各路大神的代码复杂了一些,也相对丑一些。

class Solution:
    def jump(self, nums: List[int]) -> int:
        if len(nums) <= 1: return 0
        i = 0
        jump = 0
        while i < len(nums) and i+nums[i] < len(nums)-1:
            j = i + 1
            reach = 0
            max_index = 0
            while j <= i + nums[i] and j < len(nums):
                if j < len(nums) and nums[j]+j > reach:
                    reach = nums[j]+j 
                    max_index = j
                j += 1
            i = max_index
            jump += 1
            # print(i)
        return jump+1

可以参考简洁版:

https://leetcode.com/problems/jump-game-ii/discuss/170518/8-Lines-in-Python!-Easiest-Solution!

https://leetcode.com/problems/jump-game-ii/discuss/18014/Concise-O(n)-one-loop-JAVA-solution-based-on-Greedy

核心思想是用记录范围、更新范围

猜你喜欢

转载自www.cnblogs.com/sbj123456789/p/12199461.html