1.6 面试经典150题 - 跳跃游戏

跳跃游戏

给你一个非负整数数组 nums ,你最初位于数组的 第一个下标 。数组中的每个元素代表你在该位置可以跳跃的最大长度。

判断你是否能够到达最后一个下标,如果可以,返回 true ;否则,返回 false

python 复制代码
class Solution(object):
    
    def canJump(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        if not nums or len(nums) == 1: return True
        # 定义左右指针
        left = 0
        right = left + 1
        while right < len(nums):
            tmp_right = left
            # 计算本轮最有可以到达的位置
            for i in range(left, right):
                pos = i + nums[i]
                # 可以到达最后一个元素,提前返回
                if pos >= len(nums) - 1: return True
                if pos > tmp_right: tmp_right = pos
            # 本轮不能再向右了,返回false
            if tmp_right < right: return False
            # 更新两个指针值
            left = right
            right = tmp_right + 1
        return True

本题解题思路:

记录两个值:当前位置left,和目前可以到达的最右位置right

每次对区间内的位置进行遍历,找到新的 可以到达的最右位置

如果不能继续向右,则无法到达最后一个节点

如果可以,则更新left 和 right位置,继续遍历

跳跃游戏II

给定一个长度为 n0 索引 整数数组 nums。初始位置为 nums[0]

每个元素 nums[i] 表示从索引 i 向前跳转的最大长度。换句话说,如果你在 nums[i] 处,你可以跳转到任意 nums[i + j] 处:

  • 0 <= j <= nums[i]
  • i + j < n

返回到达 nums[n - 1] 的最小跳跃次数。生成的测试用例可以到达 nums[n - 1]

python 复制代码
class Solution(object):
    def jump(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums or len(nums) == 1: return 0
        count = 0
        left = 0
        right = left + 1
        while right < len(nums):
            count += 1
            tmp_right = left
            for i in range(left, right):
                pos = i + nums[i]
                if pos >= len(nums) - 1: return count
                if pos > tmp_right: tmp_right = pos
            if tmp_right < right: return -1
            left = right
            right = tmp_right + 1
        return count

本题对上题略加修改,每次遍历都将计数加1,在上一题返回return的位置,变为返回计数即可。

相关推荐
IVEN_3 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang5 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮5 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling5 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮8 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽8 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健1 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞1 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽1 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers