45. Jump Game II python

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.

 

题意:算出跳的最小次数

思路:这个题和Jump Game类似。Jump Game是判断是否能调到终点,这个是假设能调到终点,算出最小的次数。

我沿用Jump Game的思路:把当前数存进flag中,每往前进一个,就减1,然后判断经过的位置对应的值和flag谁大,存大的。(表示能走的最远的距离)。一个for下来,最后的index变成最后一个数,而flag代表当前能走的最远的距离。其中有个坑:并不是每次存入大值都要把result+1,而是一次for循环下来才加(一次for循环下来可能有好几次赋值)。

反思该题的思路应该是贪心算法,每次往前走,都找到最大能走的距离存下来。一轮贪心下来,result+1,最后返回总的贪心次数

还有一个坑需要注意:由于中间调试bug,用了print,结果一直显示超时,最后才发现是由于循环print太多,导致的超时。

class Solution(object):
    def jump(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        
        if(len(nums)==1):
            return 0
        flag=nums[0]
        temp=flag
        index=0
        length=len(nums)-1
        count=0
        while(1):
            if(index+temp>=length):
                count+=1
                return count            
            #从第一个索引值范围内,挑一个最大的
            for i in range(index+1,index+flag+1):
                temp-=1
                if(nums[i]>temp):
                    temp=nums[i]          
            count+=1            
            index=index+flag
            flag=temp

     

 

你可能感兴趣的:(leetcode)