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

     

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值