LeetCode #55jump game

'''
#55jump games
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.
分析:如果全为正数,不论如何都能到达
      当且仅当一串0超过前边的最远到达范围,才会出现失败
自然语言描述
    从第一个index开始遍历:
      对于每一个元素: 如果max < index+arr[index] ,则将其设为max
                       else max == index+arr[index]&&arr[index] == 0 ,                             return false
pre: a list of int -- arr
post: if we can arrive the last index
max <- 0
for i <- 0 to arr.size-2:
    if max < index+arr[index]:
        max <- index+arr[index]
    else if max = index+arr[index]:
             return false
return true
证明:
    如果不能到达,设数组序列为S1S2S3
        其中S2全为0,S1最后一个非0 , S3第一个非0
    S1中所能到达的最远距离设为L
        如果L <= index(S2.right),则不能到达
        否则能够到达S3

注意,数组最后一个元素不会产生影响:需要将其排除,避免其它讨论
'''

def canJump(nums):
    """
    :type nums: List[int]
    :rtype: bool
    """
    Max = 0
    for i in range(0,len(nums)-1 ):
        if ( Max < i + nums[i] ):
            Max = i + nums[i]
        elif ( Max == i+nums[i] and not nums[i])
            return False
    return True
           

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值