leetcode55 跳跃游戏

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012343179/article/details/89855898

这道题如果采用循环的方式,每次记录下一跳能到哪里,则时间复杂度为O(n^2),太慢了。

因此,我们需要想更加简单的方法。

我们发现,当经过某一跳时,我们可以知道通过这一跳之后能达到的最远距离,只要这个最远距离能够达到最后一个即可。因此,我们每经过一跳,我们就看下能不能到最远,如果能则返回True,不能的话我们就记录下当前能跳到的最远,然后继续判断能否跳到下一个点。

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        temp_max=0#当前最远距离
        target=len(nums)-1
        i=0
        while i<=temp_max:
            if i+nums[i]>=target:
                return True
            else:
                temp_max=max(temp_max,i+nums[i])
            i+=1
        return False

猜你喜欢

转载自blog.csdn.net/u012343179/article/details/89855898