CPP-SCNUOJ-Problem P24. [算法课贪心] 跳跃游戏

Problem P24. [算法课贪心] 跳跃游戏
给定一个非负整数数组 nums ,你最初位于数组的 第一个下标 。

数组中的每个元素代表你在该位置可以跳跃的最大长度

判断你是否能够到达最后一个下标。

输入

输入一行数组nums

输出

输出true/fasle

样例

标准输入
2 3 1 1 4
标准输出
true
标准输入
3 2 1 0 4
标准输出
false

解题思路

在这里插入图片描述

参考文章

#include <iostream>
#include <bits/stdc++.h>

using namespace std;

bool game(vector<int> &arr)
{
    int n = arr.size();
    int max_pos = 0; // 记录到达的最大位置,初始位置0,数组第一位
    if(n <= 1) // 数组只有一个数字,即到达了
        return true;
    for(int i=0; i<n-1; i++) // 遍历数组
    {
        if(i <= max_pos) // 如果数组当前的位置比到达的最大位置大,说明到不了该位置,就是false
        {
            max_pos = max(max_pos, i+arr[i]); // i位置一定可以到达,此时选此位置跳跃和目前的max位置进行比较,再取max
            if(max_pos >= n-1) // 跳出数组,则ok
            {
                return true;
            }
        }
        else
        {
            return false;
        }
    }
}

int main()
{
    int n;
    vector<int> arr;
    while(cin >> n) // 数组中出现0则
    {
//        if(n == 0)
//        {
//            cout << "false";
//            return 0;
//        }
//        else
        {
            arr.push_back(n);
        }
    }
    bool flag = game(arr);
    if(flag)
    {
        cout << "true";
    }
    else
    {
        cout << "false";
    }
//    cout << "Hello world!" << endl;
    return 0;
}

自我练习,二刷

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
/*
思路:数组只有一个数字,直接到达目的地;
      对数组进行遍历,数组最后一位不需要遍历;
        遍历当前数组位置i要在可跳跃最大位置里面;
        更新跳跃最大位置max(最大位置,i+nums[i]);
        如果最大位置超过了数组最后一位,即n-1,则跳跃成功;
*/
int main()
{
    vector<int> nums;
    int x;
    while(cin >> x)
    {
        nums.push_back(x);
    }
    int n = nums.size();//数组长度
    if(n <= 1)
    {
        cout << "true";
        return 0;
    }
    int maxp = 0;//初始跳跃最大位置为0;
    for(int i=0; i<n-1; i++)
    {
        if(i <= maxp)
        {
            maxp = max(maxp, nums[i]+i);
            if(maxp >= n-1)
            {
                cout << "true";
                return 0;
            }
        }
    }
    //没有经历上面的for循环,即到达不了末尾,直接false;
    cout << "false";
//    cout << "Hello world!" << endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值