Jump Game

作者: 静水流深ylyang | 来源:发表于2018-12-24 16:38 被阅读0次

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


题目描述

  • Jump Game

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], returnfalse.

题目大意

给定一个非负整数数组,最初的位置是该数组的第一个索引位置。
数组中的每个元素值表示该位置的最大跳跃长度。
确定是否能够达到最后一个索引位置。
例如:
a=[2,3,1,1,4],返回 true。
A=[3,2,1,0,4],返回 false。

思路

定义一个max_reach变量,表示最大能够达到的位置,然后遍历数组元素,每次到达一个索引位置后,判断大年索引位置加上当前索引位置的元素的值A[ i ] + i是否大于max_reach,如果大于就更新max_reach的值。
数组元素遍历的一个条件是max_reach >= i,表示此时能够调到i处。
最后判断,max_reach >= n-1表示能够调到最后一个位置。

代码

#include<iostream>
using namespace std;

bool canJump(int A[], int n)
{
    int max_reach = 0; // max标记能跳到的最远处

    // max_reach>=i表示此时能跳到i处,
    // 0<=i<n表示扫描所有能到达的点,在改点处能跳到的最远处
    for(int i=0; i<n && max_reach>=i; i++)
        if(max_reach < A[i]+i)max_reach = A[i]+i;

    // 如果最后跳的最远的结果大于等于n-1,
    // 那么满足能跳到最后。
    if(max_reach < n-1)return false;

    return true;

}

int main()
{
    int A[] = {2, 3, 1, 1, 4};
    if(canJump(A, 5))
        cout<<"true"<<endl;
    else
        cout<<"false"<<endl;
    int B[] = {3, 2, 1, 0, 4};
    if(canJump(B, 5))
        cout<<"true"<<endl;
    else
        cout<<"false"<<endl;
    return 0;
}

运行结果

以上。
[图片上传中...(image.png-fb761d-1545640540207-0)]


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


相关文章

  • [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/jrmzkqtx.html