2.贪心-跳跃游戏I

问题描述

 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.

翻译

跳跃游戏。给定一个非负整数数组,你的初始位置是数组的第一个索引。数组中的每个元素都代表你在该位置的最大跳跃长度。

判断你是否能跳到最后一个索引处。

思路

能到达的最远地方>n 则直接跳出循环

reach=max(reach,i+a[i]);

代码

#define  _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string>
#include <algorithm>
#include <stdlib.h>

using namespace std;
const int N = 1e4 + 10;
bool Jump(int a[], int n)
{
	int reach = 0;//代表目前能够到达的最远位置
	for (int i = 0; i < reach && reach < n - 1; i++)//如果i>=n还未返回false则说明reach>n
		reach = max(i + a[i], reach);//当前索引所能到达的最远位置与之前所有索引能到达的最远位置取最大值
	return true;
}
bool jumpGreedy(int a[], int n)
{
	int reach = 0;//表示能到达的最远地方
	for (int i = 0; i < n; i++)
	{
		if (i <= reach) {
			reach = max(reach, i + a[i]);
			if (reach >= n - 1)
				return true;
		}
	}
	return false;
}
int main()
{
	int n;
	cout << "Please enter The size of arr" << endl;
	cin >> n;
	int a[N];
	cout << "Please enter the arr :" << endl;
	for (int i = 0; i < n; i++)
	{
		cin >> a[i];
	}
	if (jumpGreedy(a, n))
		cout << "True" << endl;
	else
		cout << "False" << endl;
	return 0;
}

测试案例

运行结果

时间复杂度分析

只是遍历了一遍数组O(n)

速记

能到达的最远地方>n 则直接跳出循环

reach=max(reach,i+a[i]);

for (int i = 0; i < n; i++)
    {
        if (i <= reach) {
            reach = max(reach, i + a[i]);
            if (reach >= n - 1)
                return true;
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

熟人看不到

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值