求数组中的最长递增子序列

来源:互联网 发布:尘埃 mac下载 编辑:程序博客网 时间:2024/05/17 22:19

这里给出解法二的代码:

按照书上解法三的改进,作二分查找,可以将复杂度降低至O(nlogn)


/** Copyright (c) 2011 alexingcool. All Rights Reserved.*/#include <iostream>#include <iterator>#include <algorithm>#define DEBUG#undef DEBUGusing namespace std;#define INF 65535int array[] = {3, 2, 1, 2, 3};const int size = sizeof array / sizeof *array;int findLongestIncrement(int *array, int size){if (array == NULL || size <= 0)return -1;int *minValue = new int[size + 1];int maxLen = 1;minValue[1] = *array;for (int i = 1; i < size; i++){int j;for (j = maxLen; j >= 1; j--){if (array[i] < minValue[j]);elsebreak;}if (j == maxLen){maxLen = j + 1;minValue[j + 1] = array[i];}else{if (minValue[j + 1] > array[i])minValue[j + 1] = array[i];}}delete[] minValue;return maxLen;}void main(){int ret = findLongestIncrement(array, size);cout << "ret = " << ret << endl;}