Jump-Game

本文深入解析JumpGame算法问题,探讨如何通过定义max_reach变量,遍历数组元素并更新最大跳跃距离,以此判断能否从起始位置达到数组的最后一个索引。通过具体代码实现和示例,展示了算法的具体应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

  • 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;
}

运行结果

以上。


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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值