[Greedy]55. Jump Game

  • 分类:Greedy
  • 时间复杂度: O(n)

55. Jump Game

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.

Determine if you are able to reach the last index.

Example 1:

Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2:

Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
             jump length is 0, which makes it impossible to reach the last index.

代码:

方法:

class Solution:
    def canJump(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        distance=0
        length=len(nums)
        i=0
        while(i<=distance and i<length):
            distance=max(distance,i+nums[i])
            if distance>=length-1:
                return True
            i+=1
        return False

讨论:

1.挺简单的贪心算法题= 。=
2.注意边界,注意边界,注意边界,重要的事情说三遍

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,949评论 0 10
  • 蔬菜姑娘热情、开朗,还有一副迷人的笑容。比她动人外表更重要的是,她聪明善良,刻苦勤劳,对生活充满信心。村庄里的小伙...
    NeyoShinado阅读 460评论 0 0
  • 人人都喜欢故事。讲故事让演讲从仅仅有用变得引人入胜。与准确但无趣的事实和生涩的行业术语相比,精心准备的故事无疑更加...
    Jason夏爱读书阅读 457评论 0 1
  • 迭代器模式是一种相对简单的模式,简单到很多时候我们都不认为它是一种设计模式。目前的绝大部分语言都内置了迭代器。 比...
    风铭阅读 1,739评论 0 2
  • 循环结构 举一个简单的例子,比如在我们的程序中要实现每隔1秒中在屏幕上打印一个"hello, world"这样的字...
    0893051f5f11阅读 1,067评论 0 0

友情链接更多精彩内容