/* 求数组中最长的等差数列 只需要遍历字符串即可 */ #include <stdio.h> #include <iostream> using namespace std; const int N = 10; const int INVALID_IDX = -1; void show(int* a,int n) { for (int i=0;i<n;++i) { cout<<a[i]<<","; } cout<<endl; } inline int compare(const void* p1,const void* p2) { return *(int*)p1 - *(int*)p2; } void longest_seq(int* a) { qsort(a,N,sizeof(int),&compare); int R = a[N-1]-a[0]+1; pair<int,int>** dp = new pair<int,int>*[R]; for (int i=0;i<R;++i) { pair<int,int>* row = new pair<int,int>[N]; for (int j=0;j<N;++j) { row[j].first = 0; //记录当前最长数列的长度 row[j].second = INVALID_IDX;//记录与first相对应的等差数列的下一值在数组a中的索引 } dp[i] = row; } int maxlen = 0; int rowidx = INVALID_IDX; int colidx = INVALID_IDX; for (int i=N-2;i>=0;--i) { for (int j=i+1;j<N;++j) { if (dp[ a[j]-a[i] ][i].first != 0) continue; //以该差为行号的值如果已经存在,就不需要再为相同的差值更新 dp[ a[j]-a[i] ][i].first = dp[ a[j]-a[i] ][j].first + 1; dp[ a[j]-a[i] ][i].second = j; if (dp[ a[j]-a[i] ][i].first > maxlen) { maxlen = dp[ a[j]-a[i] ][i].first; rowidx = a[j]-a[i]; colidx = i; } } } if( maxlen > 1 ) { cout<<"The longest:"<<endl; while( colidx != INVALID_IDX ) { cout<<a[colidx]<<","; colidx = dp[rowidx][colidx].second; } cout<<endl; } else { cout<<"0,0"<<endl; } for (int i=0;i<R;++i) delete []dp[i]; delete []dp; } int main(void) { int a[N] = {8, 8, 7, 4, 1, 3, 3, 1, 8, 4}; longest_seq(a); system("pause"); return 0; }
代码下载地址:http://download.csdn.net/detail/yincheng01/6704519
解压密码:c.itcast.cn
下载代码并解压后,用VC2013打开interview.sln,并设置对应的启动项目后,点击运行即可,具体步骤如下:
1)设置启动项目:右键点击解决方案,在弹出菜单中选择“设置启动项目”
2)在下拉框中选择相应项目,项目名和博客编号一致
3)点击“本地Windows调试器”运行