鱼儿慢慢游~~

导航

 

题目描述:

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. 

For example:
 A = [2,3,1,1,4], return true. 

A = [3,2,1,0,4], return false. 

即, 给定一组非负数, 每一个数字代表可以向后走的最大步数, 如A= [2, 3, 1, 1, 4], A[0] = 2, 代表从A[0]可以访问到(A[1] = 3, A[2] =1), 同理,类推。

如果从第一个数开始, 按上述方法, 可以访问到最后一个数, 则该数组返回True, 否则返回False。

思路:

对于数字可访问的区间,我们记录并更新最大可访问的index
如 A[0] = 2, 可访问的区间为(0, 1, 2),最大访问的index = 2, 接下来访问该区间内的下一个数字,A[1] = 3, 则A[1] 可访问的区间为 (1, 2, 3, 4),
最大访问index 更新为4,4 已经是数组的最后一个元素了,则返回True, 否则继续遍历。 更新最大访问的index

代码如下:

class Solution(object):
    def canJump(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        l = len(nums)
        if l == 0 or l == 1:
            return True
        step = nums[0] + 0
        if step >= l-1:
            return True
        i = 1
        while i < step+1:
            maxStep = nums[i] + i  #当前数字可访问的最大index
            if maxStep >= l-1:
                return True
            step = max(maxStep, step)
            i = i + 1
        return False

 

posted on 2016-07-27 09:50  miss_UU  阅读(149)  评论(0编辑  收藏  举报