Description
给定一个非负整数数组,假定你的初始位置为数组第一个位置。数组中的每个元素代表你在那个位置能够跳跃的最大长度。你的目标是到达最后一个下标位置,并且使用最少的跳跃次数。
Input
输入一组非负整数数组,数组长度不超过500。
Output
最少经过几次跳跃,可以到达最后一个位置。
Sample Input
2 3 1 1 4
Sample Output
2
算法思想
每次都遍历当前位置所能到达的位置,跳到数字最大即可
#include<iostream>
using namespace std;
int main()
{
int arr[511];
int n = 0;
int k;
// 输入
while(cin >> k)
{
char x = cin.get();
arr[n++] = k;
if(x == '\n')
break;
}
int i=0;
int count = 0;
if(n==1)
{
cout << 0 << endl;
return 0;
}
while(true)
{
//如果当前位置可以直接跳到终点
if(i+arr[i]>=n-1)
{
count++;
break;
}
// 找到当前位置所能跳跃范围内最大的数
int maxNum = -1;
int maxIndex;
for(int j=i+1; j<=i+arr[i]; j++)
if(arr[j]>maxNum)
{
maxNum = arr[j];
maxIndex = j;
}
i = maxIndex; // 跳跃到最合适的位置
count++;
}
cout << count << endl;
return 0;
}