Jump Game

作者: 瞬铭 | 来源:发表于2019-08-28 14:05 被阅读0次

https://leetcode.com/problems/jump-game-ii/
给定一个数组nums,数组内部都是正整数,每走到数组的index,则表明可以继续往后最大走nums[i]步,求最少需要走过多少个index则能走到最后
示例:[2,3,1,1,4]
答:2
解析:从2走到3,从3走到4,一共经过了两个index

  • 解析
    两个指针,pre代表上一次能够达到的最远距离,cur表明当前能达到的最远距离,所以当cur< nums.length -1的时候,表明此时还没达到最后一个index,需要继续循环。结果用一个变量res来标明,因为本题只用算从最开始到最后需要走多少步,随意每循环,res就对应+1

input:[2,3,1,1,4]

  1. res = 1; pre = 0; cur = 2,i=0
    2.res=2;pre=2;cur=5;i=2
    return 2
    public int jump(int[] nums) {
                int pre = 0;//上一次循环达到的最远距离
        int cur = 0;//本次计算达到的最远距离
        int len = nums.length;
        int res = 0;//结果int,表明需要做多少步
        int i = 0;//用来循环的游标
        while (cur < len - 1) {//只要cur没有达到最后一个index,则继续循环
            res++;//每次循环,表明多走了一步,需要将res加一
            pre = cur;//更新上次走到的距离
            for (; i <= pre; i++) {//因为每次pre都会更新,即会往后走,所以在上次走到的游标i为基准,重新算走到的更远距离
                cur = Math.max(cur, i + nums[i]);
            }
        }
        return res;
    }

相关文章

  • [DP]45. Jump Game II

    前篇 55. Jump Game 45. Jump Game II 感谢Jason_Yuan大神优秀的解析:链接 ...

  • Custer Jump

    Custer Jump is a jumping game, you will love this game. T...

  • Jump Game

    这道题有点像大富翁呀,题意也很简单明确,就不解释了。我首先想到的就是用迭代遍历硬杠它。从最大值开始跳,每个位置都是...

  • Jump Game

    Jump Game 题目分析:找出能够到达的最远距离是否能到最后一个索引。我的想法是从第一个开始,不断更新最长到达...

  • Jump Game

    Jump Game 今天是一道有关贪婪算法的题目,来自LeetCode#55,难度为Medium,Acceptan...

  • Jump Game

    https://leetcode.com/problems/jump-game-ii/给定一个数组nums,数组内...

  • Jump Game

    版权声明:本文为博主原创文章,转载请注明出处。个人博客地址:https://yangyuanlin.club欢迎来...

  • 坐标型--(b)跳格子

    1) jump game I, II (LeetCode 55, 45) [ 要求] 给出jump power数组...

  • 2019-02-02 第六天(#55, #45)

    #55 Jump Game 题目地址:https://leetcode.com/problems/jump-gam...

  • GO!MY PET

    This is a very interesting adventure game. Move to jump, ...

网友评论

      本文标题:Jump Game

      本文链接:https://www.haomeiwen.com/subject/atyrectx.html