【leetcode】55. Jump Game

The topics are as follows:

Problem- solving idea: This problem is very similar to the stair climbing problem. I tried to use dynamic programming at first, and the result was TEL. Then carefully analyze the question, the question only requires to judge whether it can be reached, which is very critical. In this case, we need to judge whether there is at least one index, and the farthest distance it can reach is greater than the length of the array. But be careful, the array may be disconnected in the middle, such as [1, 2, 0, 0, 4, 5], so you need to use an intermediate variable to record whether each index is reachable.

code show as below:

class Solution(object):
    def canJump(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """ 
        farest = 0
         for i,v in enumerate(nums):
             #This if indicates that there is a disconnection in the middle of the array, the element cannot be reached, return false 
            if farest < i:
                 return False
             #Update the farthest record that can be reached 
            if farest < i + v:
                farest = i + v
             #Determine whether it is greater than the length of the array 
            if farest >= len(nums) - 1 :
                 return True
         return False

 

Guess you like

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