LeetCode Jump Game II
来源:互联网 发布:正交矩阵一定是方阵吗 编辑:程序博客网 时间:2024/06/11 07:51
LeetCode解题之Jump Game II
原题
数组中的每个值表示在当前位置最多能向前面跳几步,判断至少跳几步能够跳到最后。
注意点:
- 所有的数字都是正数
- 跳的步数可以比当前的值小
- 保证所有的测试用例都能够跳到最后
例子:
输入: nums = [2, 3, 1, 1, 4]
输出: 2
解题思路
这是在 Jump Game 之上给出的问题,题目已经保证能够跳到最后。遍历数组,起始到当前坐标所有跳跃方式能够到达的最远距离是reach,我们跳n步能到达的最远距离用longest表示,如果longest不能到达当前坐标,说明就要多跳一步了,直接跳到当前坐标之前的点能够跳到的最远位置。
AC源码
class Solution(object): def jump(self, nums): """ :type nums: List[int] :rtype: int """ length = len(nums) counter = 0 longest = 0 reach = 0 for i in range(length): if longest < i: counter += 1 longest = reach reach = max(reach, nums[i] + i) return counterif __name__ == "__main__": assert Solution().jump([2, 3, 1, 1, 4]) == 2
欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。
0 0
- LeetCode: Jump Game II
- LeetCode Jump Game II
- LeetCode: Jump Game II
- [Leetcode] Jump Game II
- [LeetCode] Jump Game II
- [Leetcode] Jump Game ii
- leetcode Jump Game II
- leetcode Jump Game II
- [LeetCode]Jump Game II
- [leetcode]Jump Game II
- LeetCode-Jump Game II
- [leetcode] Jump Game II
- LeetCode - Jump Game II
- LeetCode:Jump Game II
- LeetCode | Jump Game II
- 【Leetcode】Jump Game II
- LeetCode Jump Game II
- [LeetCode] Jump Game II
- unity 在ios上的 c#键值对数据排序
- SVN 简单使用方法
- /etc/hosts文件修改后如何生效
- Twisted 线程
- 同样遇到PHP 连接SQL2008 查询出现中文乱码问题
- LeetCode Jump Game II
- CentOS 下载地址
- 原生js和jquery实现图片轮播特效
- Linux养成计划: vi编辑器
- Swift-数组
- CSS常用选择器学习
- 代码要为现实服务
- 移动web应用开发——Sencha Touch篇(1)
- Swift-元组(Tuple)