#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
// 方法一:vector<pair<int,int>>有序数组统计法,时间复杂度n^2
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
vector<pair<int, int>> statistic;
int returnMax = 0;
for (int i = 0; i < nums.size(); ++i) {
int j, tempMax = 0;
for (j = 0; j < statistic.size(); ++j) {
if (statistic[j].first >= nums[i]) {
break;
}
else {
tempMax = statistic[j].second > tempMax ? statistic[j].second : tempMax;
}
}
tempMax += 1;
returnMax = tempMax > returnMax ? tempMax : returnMax;
statistic.insert(statistic.begin() + j, { nums[i],tempMax });
}
return returnMax;
}
};
// 方法二:网友答案,动态规划法DP(比较难想),用到了c++ 中lower_bound()函数(返回大于等于val值的第一个元素的位置,底层算法用到了有序队列二分法查找),时间复杂度nlogn
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
if (nums.size() == 0) return 0;
vector<int> DP;
DP.push_back(nums[0]);
for (int i =1 ; i < nums.size(); ++i) {
if (nums[i] > DP.back()) {
DP.push_back(nums[i]);
}
else {
*(lower_bound(DP.begin(), DP.end(), nums[i])) = nums[i]; //直接替换返回位置的元素,同时因为数列是有序的,所以可以用二分查找的算法lower_bound
}
}
return DP.size();
}
};
//用到二分查找的c++STL库函数有:lower_bound()、upper_bound()、equal_range() 以及 binary_search()