O(N^2)算法 #include<stdio.h> #include<stdlib.h> #include<memory.h> #include "assert.h" void Longest(int *arr ,int len ) { int *pArrPre = ( int*)malloc( len* sizeof( int)); int *pArrLen = ( int*)malloc( len* sizeof( int)); int maxLen = 1; int maxIndex = 1; for(int iLoopTarget = 0;iLoopTarget< len;iLoopTarget++){ pArrLen[iLoopTarget] = 1; pArrPre[iLoopTarget] = -1; for(int iLoop = 0;iLoop < iLoopTarget;iLoop++){ if( arr[iLoopTarget]> arr[iLoop] && pArrLen[iLoop]+1>pArrLen[iLoopTarget]){ pArrLen[iLoopTarget] = pArrLen[iLoop] + 1; pArrPre[iLoopTarget] = iLoop; } } if(pArrLen[iLoopTarget]>maxLen){ maxLen = pArrLen[iLoopTarget]; maxIndex = iLoopTarget; } } while(maxIndex>=0){ printf("%3d ", arr[maxIndex]); maxIndex = pArrPre[maxIndex]; } free(pArrPre);free(pArrLen); } int main() { int arr[] = {3,4,5,3,9,5,6,8,9,0,3,4,6,3,6,4,6,3,5,7,8,2}; Longest(arr,sizeof(arr)/sizeof(arr[0])); return 1; } O(NlgN)算法 #include<stdio.h> #include<stdlib.h> #include<memory.h> #include "assert.h" void print(int *arr,int len); void Longest(int *arr ,int iLen ) { int *pArrPre = ( int*)malloc( iLen* sizeof( int)); //存储前一个数字的索引,通过这个ArrPre获取增长子序列 int *pArrSort = ( int*)malloc(( iLen+1)* sizeof( int)); //排序的数值 int *pArrSortIndex = ( int*)malloc(( iLen+1)* sizeof( int)); //排序数值所对应的index,为pArrPre服务 pArrSort[0] = -10000; //INT_MIN pArrSortIndex[0] = -1; int maxIndexSort = 0; for (int iLoopTarget = 0; iLoopTarget <= iLen; iLoopTarget++) { pArrPre[iLoopTarget] = -1; for( int iLoop = maxIndexSort; iLoop >= 0; iLoop--) { //用二分法查找,就可以做到NlogN的时间复杂度了 if(pArrSort[iLoop]< arr[iLoopTarget]){ pArrSort[iLoop+1] = arr[iLoopTarget]; pArrSortIndex[iLoop+1] = iLoopTarget; pArrPre[iLoopTarget] = pArrSortIndex[iLoop]; if(iLoop+1>maxIndexSort) maxIndexSort = iLoop+1; break; } } } //Print All Log Data print(arr,iLen); print(pArrPre,iLen); print(pArrSort,iLen); print(pArrSortIndex, iLen); int idxMax = pArrSortIndex[maxIndexSort]; while (idxMax>=0) { printf( "%d ",arr [idxMax]); idxMax = pArrPre[idxMax]; } free(pArrPre); free(pArrSortIndex); free(pArrSort); } void print(int *arr ,int len ) { int iLoop; for(iLoop = 0;iLoop < len;iLoop++) { printf( "%3d ",arr [iLoop]); } printf(" "); } int main() { int arr[] = {3,4,5,3,9,5,6,8,9,0,3,4,6,3,6,4,6,3,5,7,8,2}; Longest(arr,sizeof(arr)/sizeof(arr[0])-1); return 1; }