最长递增子序列,这是一个动态规划的典型问题,正好可以应用这次课上讲的算法。
在我的实现中,使用了遍历来查找辅助数组中的元素,看两个for循环就可以知道,算法的复杂度应该是O(n^2)。题目说可以找出一个O(nlogn)的解法,我觉得可能是因为辅助数组里存储的其实就是一个递增子序列,也就是有序的序列,可以使用二分查找,那样的效率会高很多,查找效率从O(n)下降到O(logn),总体的时间复杂度可以下降到O(nlogn)。
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
vector<int> d;
if (nums.empty())
return 0;
d.push_back(nums[0]);
for (unsigned int i = 1; i < nums.size(); ++i) {
if (nums[i] > d.back())
d.push_back(nums[i]);
else {
for (unsigned int j = 0; j < d.size(); ++j) {
if (d[j] >= nums[i]) { // 如果是>,则是求最长不减子序列
d[j] = nums[i];
break;
}
}
}
}
// 输出最长递增子序列
// for (unsigned int i = 0; i < d.size(); ++i)
// cout << d[i] << " ";
// cout << endl;
return d.size();
}
};
int main(int argc, char const *argv[]) {
int n = 6;
int arr[] = {4, 10, 4, 3, 8, 9};
vector<int> a(arr, arr + n);
Solution s;
cout << s.lengthOfLIS(a) << endl;
return 0;
}