格式:
输入[1,3,0,5,-1,6]
输出[-1,1,3,5]
要求时间复杂度,空间复杂度尽量小
第一反应还是动态规划,我们可以先将数组排序,然后建立一个二维数组,来记录每一个输入数组中的数字和比他小的数字所有的相减结果的当前最长等差数列长度。我们用n代表当前的数字,d代表等差数列的差值。于是f(n,m) = f(n-m,m) + 1。 f(n-m,m)为比n小m的数字所包含的等差数列的长度。当然如果f(n-m,m)不存在则f(n,m)赋值为1。于是我们只要记录拥有最长的等差数列的数字n,m以及等差数列的长度s,我们就可以列出等差数列n,n-m,n-2*m…n-s*m
#include <map>
void qsort(int * arr, int length)
{
if(length <2 || NULL == arr)
{
return;
}
int flag = arr[length-1];
int* p = arr;
int* q = arr;
while(p <= arr + length - 1 )
{
if(*p <= flag)
{
int temp = *q;
*q = *p;
*p = temp;
++q;
++p;
}
else
{
++p;
}
}
qsort(arr,q - arr - 1);
qsort(q, length - (q - arr));
}
void ArithmeticSequence(int * arr, int length)
{
if(NULL == arr || length < 1)
{
printf("[0,0]");
}
qsort(arr,length);
std::map<int,int>* mapAS = new std::map<int,int>[length];
int maxNum = arr[0];
int maxDiff = 0;
int maxLen = 1;
for(int i = 1; i < length; ++i)
{
for(int j = 0; j < i; ++j)
{
int diff = arr[i] - arr[j];
if(mapAS[j].find(diff) != mapAS[j].end())
{
mapAS[i][diff] = mapAS[j][diff] + 1;
}
else
{
mapAS[i][diff] = 1;
}
if(maxLen < mapAS[i][diff])
{
maxLen = mapAS[i][diff];
maxNum = arr[i];
maxDiff = diff;
}
}
}
printf("[");
printf("%d",maxNum - maxLen * maxDiff);
for(int i = maxLen - 1;i >= 0; --i)
{
printf(",%d",maxNum - maxDiff * i);
}
printf("]");
delete [] mapAS;
}