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的位置,变为返回计数即可。

相关推荐
MediaTea14 小时前
Python 文件操作:JSON 格式
开发语言·windows·python·json
百锦再14 小时前
金仓数据库提出“三低一平”的迁移理念
开发语言·数据库·后端·python·rust·eclipse·pygame
野生工程师14 小时前
【Python爬虫基础-1】爬虫开发基础
开发语言·爬虫·python
力江14 小时前
攻克维吾尔语识别的技术实践(多语言智能识别系统)
人工智能·python·自然语言处理·语音识别·unicode·维吾尔语
诗句藏于尽头15 小时前
MediaPipe+OpenCV的python实现交互式贪吃蛇小游戏
人工智能·python·opencv
盼哥PyAI实验室15 小时前
Python 正则表达式实战 + 详解:从匹配QQ邮箱到掌握核心语法
python·mysql·正则表达式
木易 士心15 小时前
Android 开发核心技术深度解析
android·开发语言·python
nju_spy15 小时前
力扣每日一题(四)线段树 + 树状数组 + 差分
数据结构·python·算法·leetcode·面试·线段树·笔试
lzq60315 小时前
Python虚拟环境全指南:venv与conda对比与实践
开发语言·python·conda
Candice_jy16 小时前
vscode运行ipynb文件:使用docker中的虚拟环境
服务器·ide·vscode·python·docker·容器·编辑器