前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode: 45. Jump Game II

leetcode: 45. Jump Game II

作者头像
JNingWei
发布2018-09-27 17:13:01
5640
发布2018-09-27 17:13:01
举报
文章被收录于专栏:JNing的专栏JNing的专栏

Problem

代码语言:javascript
复制
# Given an array of non-negative integers, 
# you are initially positioned at the first index of the array.
#
# Each element in the array represents your maximum jump length at that position.
#
# Your goal is to reach the last index in the minimum number of jumps.
#
# For example:
# Given array A = [2,3,1,1,4]
#
# The minimum number of jumps to reach the last index is 2. 
# (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
#
# Note:
# You can assume that you can always reach the last index.

Idea

代码语言:javascript
复制
二指针问题,最大覆盖区间。
从左往右扫描,维护一个覆盖区间,每扫过一个元素,就重新计算覆盖区间的边界。
比如,开始时区间[start, end], 遍历A数组的过程中,不断计算A[i]+i最大值(即从i坐标开始最大的覆盖坐标),
并设置这个最大覆盖坐标为新的end边界。
而新的start边界则为原end+1。不断循环,直到 end > n.

AC

代码语言:javascript
复制
class Solution():
    def jump(self, x):
        if len(x) > 1:
            pre, step = [0], 0
            while True:
                step += 1
                left = right = pre[-1] + 1
                for p in pre:
                    if p + x[p] > right:
                        right = p + x[p]
                if right >= len(x)-1:
                    return step
                pre = range(left, right+1)
        return 0


if __name__ == "__main__":
    assert Solution().jump([2,3,1,1,4]) == 2
    assert Solution().jump([3,2,1,0,4]) == 2
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年11月14日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

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

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

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