[Leetcode]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.

Note:

You can assume that you can always reach the last index.

An ingenious and not easy to understand greedy algorithm can achieve the time complexity of O(N), but in the algorithm it is necessary to record the farthest distance that the current hop can reach and the farthest distance that the previous hop can reach. , and the number of hops currently in use.

class Solution(object):
    def jump(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        ret = 0 #current hop count
        last = 0 #The last hop can reach the farthest distance
        cur = 0 #The current jump can reach the farthest distance
        for i in range(len(nums)):
            if i > last: #Need to make the next jump, update last and jump count ret
                last = cur
                ret + = 1
            cur = max(cur, i+nums[i]) #Record the farthest point currently reachable
        return right
        


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324829333&siteId=291194637