美文网首页
Jump Game问题

Jump Game问题

作者: juexin | 来源:发表于2017-02-17 17:04 被阅读0次

Jump Game I
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.
Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int reach = 0;
        
        for(int i=0;i<=reach;i++)  //特别注意这个reach
        {
            reach = max(reach,nums[i]+i);
            if(reach>=nums.size()-1)
              return true;
        }
        return false;
    }
};

**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.)
Note:
You can assume that you can always reach the last index.

class Solution {
public:
    int jump(vector<int>& nums) {
        int rec = 0;
        int curRch = 0;
        int curMax = 0;
        for(int i=0;i<nums.size();i++)
        {
            if(curRch<i)  //特别注意这个判断条件
            {
                rec++;
                curRch = curMax;
            }
            curMax = max(curMax,nums[i]+i);
        }
        return rec;
    }
};

相关文章

  • Jump Game问题

    Jump Game IGiven an array of non-negative integers, you a...

  • [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...

网友评论

      本文标题:Jump Game问题

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