算法提高之LeetCode刷题数据结构和算法分析

跳跃游戏

2020-04-17  本文已影响0人  _阿南_

题目:

给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个位置。
示例 1:
输入: [2,3,1,1,4]
输出: true
解释: 我们可以先跳 1 步,从位置 0 到达 位置 1, 然后再从位置 1 跳 3 步到达最后一个位置。
示例 2:
输入: [3,2,1,0,4]
输出: false
解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。

题目的理解:

从index为0开始跳,看是否能跳到最后一位。那么可以反过来思考,从最后一位A向后查,是否有一位B能够跳到当前的位置A,如果没有一直向后查,如果有那么将位置A移动到位置B,继续查。

python实现

from typing import List

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        nums.reverse()
        index = 0
        
        while index < len(nums):
            length = 1
            found = False
            while True:
                if index + length >= len(nums):
                    break
                
                if nums[index + length] >= length:
                    index += length
                    found = True
                    break
                
                length += 1

            if not found:
                if index + length >= len(nums):
                    break

        return index == len(nums) - 1

想看最优解法移步此处

提交

One time

成绩虽然不怎么样,但是第一性通过,真的是太难得了。 激动到哭。。。

// END 人生最难得的是找到自己的定位,发现自己的兴趣

上一篇 下一篇

猜你喜欢

热点阅读