//判断JollyJumper序列
#include <iostream>
#include <assert.h>
using namespace std;
bool JollyJumper(int a[],int n)
{
assert(a != NULL || n >= 2);
int sum = (n-1)*n/2;//求出1+2+……+n-1的值
for(int i=0; i != n-1; ++i)
{
int x = (a[i] > a[i+1]) ? (a[i]-a[i+1]) : (a[i+1] - a[i]);
sum -= x;
}
return (0==sum) ? true : false;
}
int main()
{
int arr[] = {1,2,4,7,11,16,22,29,37,46};//yes
int arr2[] = {1,2,4,7,11,16,22,29,37,45};//no
int arr3[] = {1,2,0,3,7,2,8,1,9,0};//yes
cout << (JollyJumper(arr3,sizeof(arr3)/sizeof(arr3[0])) ? "yes" : "no");
}
时间复杂度为:O(n)
空间复杂度为:O(1)