前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【leetcode刷题】20T24-跳跃游戏

【leetcode刷题】20T24-跳跃游戏

作者头像
木又AI帮
发布2020-02-27 15:28:41
3460
发布2020-02-27 15:28:41
举报
文章被收录于专栏:木又AI帮木又AI帮

木又同学2020年第24篇解题报告

leetcode第55题:跳跃游戏

https://leetcode-cn.com/problems/jump-game


【题目】

给定一个非负整数数组,你最初位于数组的第一个位置。

数组中的每个元素代表你在该位置可以跳跃的最大长度。

判断你是否能够到达最后一个位置。

示例 1:
输入: [2,3,1,1,4]
输出: true
解释: 我们可以先跳 1 步,从位置 0 到达 位置 1, 然后再从位置 1 跳 3 步到达最后一个位置。

示例 2:
输入: [3,2,1,0,4]
输出: false
解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。

【思路】

遍历数组,使用变量farthest存储当前元素能够到达的最远位置,如果i大于farthest,表明不可能到大该位置;如果i + nums[i]大于farthest,则更改farthest的值。最后比较farthest和len(nums) - 1的大小。

【代码】

python版本

class Solution(object):
    def canJump(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        farthest = 0
        for i, n in enumerate(nums):
            if i > farthest:
                return False
            if i + n > farthest:
                farthest = i + n
        return farthest >= len(nums) - 1

C++版本

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int farthest = 0;
        for (int i = 0; i < nums.size(); i++) {
            if (i > farthest)
                return false;
            if (i + nums[i] > farthest)
                farthest = i + nums[i];
        }
        return farthest >= nums.size() - 1;
    }
};
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-02-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 木又AI帮 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档