算法 - 求一个数组的最长递减子序列(C++)
2017-06-17 11:59
387 查看
//**************************************************************************************************** // // 求一个数组的最长递减子序列 - C++ - by Chimomo // // 题目: 求一个数组的最长递减子序列,比方{8, 14, 6, 2, 8, 14, 3, 2, 7, 4, 7, 2, 8, 101, 23, 6, 1, 2, 1, 1}的最长递减子序列为{14。8,3。2,1}。 // // Answer: Scan from left to right, maintain a decreasing sequence. For each number, binary search in the decreasing sequence to see whether it can be substituted. // //**************************************************************************************************** #include <iostream> #include <cassert> #include <stack> using namespace std ; int BinarySearch(int *A, int nTarget, int nLen); // Find the longest decreasing sequence in array A of length nLen. void FindLongestDecreasingSequence(int *A, int nLen) { int *index = new int[nLen]; int *LDS = new int[nLen]; index[0] = A[0]; LDS[0] = 1; int indexLen = 1; for (int i = 1; i < nLen; i++) { int pos = BinarySearch(index, A[i], indexLen); index[pos] = A[i]; LDS[i] = pos + 1; if(pos >= indexLen) { indexLen++; } } int ResultLen = indexLen; for (int i = nLen; i >= 0; i--) { if(LDS[i] == ResultLen) { index[ResultLen - 1] = A[i]; ResultLen--; } } for (int i = 0; i < indexLen; i++) { cout << index[i] << " "; } delete [] index; } // Binary search nTarget in array A of length nLen. int BinarySearch(int *A, int nTarget, int nLen) { assert(A != NULL && nLen > 0); int start = 0; int end = nLen - 1; while (start <= end) { int mid = (start + end) / 2; if(nTarget > A[mid]) { end=mid-1; } else if(nTarget<A[mid]) { start=mid+1; } else { return mid; } } return start; } int main() { int A[] = {8, 14, 6, 2, 8, 14, 3, 2, 7, 4, 7, 2, 8, 101, 23, 6, 1, 2, 1, 1}; int nLen = sizeof(A) / sizeof(int); FindLongestDecreasingSequence(A, nLen); return 0; } // Output: /* 14 8 7 6 2 1 */
相关文章推荐
- 算法 - 求一个数组的最长递减子序列(C++)
- 算法习题47:求一个数组的最长递减子序列 比如{9,4,3,2,5,4,3,2}的最长递减子序列为{9,5,4,3,2}
- 数据结构——算法之(025)( 求一个数组的最长递减子序列)
- 【编程题目】求一个数组的最长递减子序列 比如{9,4,3,2,5,4,3,2}的最长递减子序列为{9,5, 4,3,2}
- 求一个数组的最长递减子序列比如{9,4,3,2,5,4,3,2}的最长递减子序列为{9,5, 4,3,2}
- 求一个数组的最长递减子序列 比如{9,4,3,2,5,4,3,2}的最长递减子序列为{9,5,4,3,2}
- 求一个数组的最长递减子序列
- 求一个数组的最长递减子序列 比如{9,4,3,2,5,4,3,2}的最长递减子序列为{9,5,4,3,2}
- 求一个数组的最长递减子序列
- 求一个数组的最长递减子序列 比如{9,4,3,2,5,4,3,2}的最长递减子序列为{9,5,4,3,2}
- 求一个数组的最长递减子序列 比如{9,4,3,2,5,4,3,2}的最长递减子序列为{9,5,4,3,2}。
- 求一个数组的最长递减子序列
- 求一个数组的最长递减子序列 比如{9,4,3,2,5,4,3,2}的最长递减子序列为{9,5,4,3,2}。
- C++[算法]给定一个具有100个元素的数组,请对该数组随机赋值1-100,不能出现重复的值
- 数组字符串那些经典算法:最大子序列和,最长递增子序列,最长公共子串,最长公共子序列,字符串编辑距离,最长不重复子串,最长回文子串
- 给一个字符串,例如”ababc",要求返回"ab"。因为"ab”连续重复出现且最长。用C/C++语言写一个函数完成该算法,给出复杂度
- 动态规划----求一个数组的最长递减序列
- 一个无聊男人的疯狂《数据结构与算法分析-C++描述》学习笔记 习题2.8 随机数组的三种生成算法(补) 将bash的实现翻译成比较纯正的bash风格
- 给定一个长度为N的数组,找出一个最长的单调自增子序列(不一定连续,但是顺序不能乱). 第二解
- 整型数组处理算法(十二)请实现一个函数:最长顺子。[风林火山]