DP: O(n^2)
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int n = nums.size();
if (n < 2) return n;
int *res = new int[n];
for (int i = 0; i < n; i++) {
int max = 1;
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j]) {
int cur = res[j] + 1;
if (cur > max) max = cur;
}
}
res[i] = max;
}
int max = 0;
for (int i = 0; i < n; i++) {
if (res[i] > max) max = res[i];
}
return max;
}
};看到的别人的解法,O(nlgn)
lower_bound返回迭代器解引用作为左值,很巧妙
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
vector<int> res;
for (int i = 0; i < nums.size(); i++) {
if (res.empty() || nums[i] > res.back()) res.push_back(nums[i]);
else *lower_bound(res.begin(), res.end(), nums[i]) = nums[i];
}
return res.size();
}
};
本文对比了两种寻找最长递增子序列的算法:动态规划(DP)的O(n^2)复杂度方法与利用二分查找的O(nlogn)复杂度方法。详细介绍了两种方法的实现步骤,通过实例演示了如何使用这些算法解决实际问题,并讨论了它们的时间复杂度和适用场景。
1381

被折叠的 条评论
为什么被折叠?



