资讯专栏INFORMATION COLUMN

LeetCode[45] Jump Game II

keelii / 2598人阅读

摘要:复杂度思路每次设置一个窗口,观察在这一步下能到达的最远距离,不断的移动这个窗口。计数,需要移动几次,才能覆盖到末尾的值。

LeetCode[45] Jump Game II

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.)

DP

复杂度
O(N^2), O(1)

思路
每次设置一个窗口,观察在这一步下能到达的最远距离,不断的移动这个窗口。计数,需要移动几次,才能覆盖到末尾的值。

代码

public int jump(int[] nums) {
    int cnt = 0, start = 0;
    int max = 0, prehigh = 0;
    while(max < nums.length - 1) {
        cnt ++;
        prehigh = max;
        for(int i = start; i <= prehigh; i ++) {
            max = Math.max(max, nums[i] + i);
        }
        start = prehigh + 1;
    }
    return cnt;
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/65250.html

相关文章

  • leetcode45. Jump Game II

    摘要:转换为广度优先算法即为我们只需要找到每一步的开始节点和结束下标,找到下一轮遍历的最大下标,如果该下标超过了数组长度,那么结束遍历,返回步数,否则将上一轮的最终节点加一作为起始节点,并将下一轮最大下标最为结束节点,继续遍历。 题目要求 Given an array of non-negative integers, you are initially positioned at the ...

    shiguibiao 评论0 收藏0
  • [LintCode/LeetCode] Jump Game I & II

    摘要:建立动规数组,表示从起点处到达该点的可能性。循环结束后,数组对所有点作为终点的可能性都进行了赋值。和的不同在于找到最少的步数。此时的一定是满足条件的最小的,所以一定是最优解。 Jump Game Problem Given an array of non-negative integers, you are initially positioned at the first index...

    rose 评论0 收藏0
  • [Leetcode] Jump Game 跳跃游戏

    摘要:代码记录下当前区域的上界,以便待会更新下一个区域的上界更新下一个区域的上界更新下一个区域的下界后续如果要求返回最短跳跃路径,如何实现可以使用,并根据一个全局最短步数维护一个全局最短路径,当搜索完所有可能后返回这个全局最短路径。 Jump Game I 最新解法请见:https://yanjia.me/zh/2019/01/... Given an array of non-negat...

    venmos 评论0 收藏0
  • leetcode55 Jump Game

    摘要:当前起点为数组中下标为零的位置,要走到数组的最后一个下标。其中,数组中每一个元素代表当前下标下可以前进的最大步数。如果最终的终点就是起始节点,那么肯定可以从其实节点找到一条路径到达终点,否则失败。 题目要求 Given an array of non-negative integers, you are initially positioned at the first index o...

    AlanKeene 评论0 收藏0
  • LeetCode 攻略 - 2019 年 7 月下半月汇总(100 题攻略)

    摘要:月下半旬攻略道题,目前已攻略题。目前简单难度攻略已经到题,所以后面会调整自己,在刷算法与数据结构的同时,攻略中等难度的题目。 Create by jsliang on 2019-07-30 16:15:37 Recently revised in 2019-07-30 17:04:20 7 月下半旬攻略 45 道题,目前已攻略 100 题。 一 目录 不折腾的前端,和咸鱼有什么区别...

    tain335 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<