64,653
社区成员
发帖
与我相关
我的任务
分享
// 最长等差数列.cpp : 定义控制台应用程序的入口点。
//
//时间和空间复杂度均为 n*n
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include <ctime>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
srand((unsigned int)time(NULL));
vector<int> v;
unsigned int n;
n = 20;
for(unsigned int x = 0;x < n;++x)
v.push_back(rand()%10);
//输入[1,3,0,5,-1,6]
/*
v.push_back(1);
v.push_back(3);
v.push_back(0);
v.push_back(5);
v.push_back(1);
v.push_back(6);
n = v.size();
*/
sort(v.begin(),v.end());
vector<map<int,int> > vDest;
vDest.resize(n);
for(unsigned int x = 1;x < n;++ x){
for(unsigned int i = 0;i < x;++ i){
vDest[x][v[x] - v[i]] = vDest[i][v[x] - v[i]] + 1;
}
}
unsigned int number,tolerance;
unsigned int iLast_Number = 0;
int iLength = 0;
for(unsigned int x = 1; x < n; ++ x){
//int iLength = 0;
for(map<int,int>::iterator p = vDest[x].begin();p != vDest[x].end();++p){
if(iLength < p->second){
number = p->second;
tolerance = p->first;
iLength = p->second;
iLast_Number = x;
}
}
}
cout<<"排序好的数列"<<endl;
for(unsigned int x = 0; x < n;++ x)
cout<<v[x]<<" ";
cout<<endl;
cout<<"最长等差数列"<<number + 1<<" tolerance"<<tolerance<<" 最后的编号(0开始)"<<iLast_Number<<endl;
//cout<<vDest[iLast_Number][tolerance]<<endl;
if(vDest[iLast_Number][tolerance] >= 3 - 1){
int val = v[iLast_Number] - tolerance * number;
for(unsigned int x = 0; x <= number; ++ x){//由于记录number从0开始,后面需要用等于修正
//如果需要如实输出实际记录的数据,则需要n lgn复杂度.
cout<<val<<" ";
val += tolerance;
}
cout<<endl;
}
else{
cout<<"没有符合要求的数据"<<endl;
}
return 0;
}