1. 程式人生 > >LeetCode-55. Jump Game

LeetCode-55. Jump Game

0.原題

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.

 

1.程式碼

class Solution:
    def canJump(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        farthest = nums[0]
        destination = len(nums)-1
        for i in range(destination):
            if nums[i] == 0:
                if farthest <= i:
                    return False
            else:
                if farthest < i + nums[i]:
                    farthest = i + nums[i]
        return True

 

2.思路

首先,不能到達終點的情況是:困在了某個等於0的點,即這個點之前的所有點都無法跨過這個點

這個很好理解,若nums中無零點,一步一步走就可以到達終點;如果有零點,在零點之前,步子大一點,跨過零點即可。

因此,我們使用for迴圈:

當前位置座標index+nums[index]就是,從index點出發,能夠到達最遠的距離。

如果碰到0點,就判斷一下:之前的所有點,能夠到達的最遠距離,是否可以跨過這個0點即可。