问题描述
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;
}
}