关键词:
最长递增子序列
问题描述:
Given an unsorted array of integers, find the length of longest increasing subsequence.
For example,
Given [10, 9, 2, 5, 3, 7, 101, 18]
,
The longest increasing subsequence is [2, 3, 7, 101]
, therefore the length is 4
. Note that there may be more than one LIS combination, it is only necessary for you to return the length.
这是一个很好玩的题目,从给定数组中得到一个最长的子序列,要求这个序列中的元素出现顺序不变,并且后面的元素要大于前面的元素。这是最长递增子序列问题。
问题分析:
可以使用一个数组rec, rec[L]表示构成长度为L的递增子序列最后一个元素的值
扫描传入的nums数组, 设k = nums[i]
当k > rec[L]时,说明长度为L,最后一个元素为rec[L]的递增子序列后面,还可以加上一个元素k,得到一个长度为L+1,最后一个元素为k的递增子序列。
若之前没有生成长度为L+1的递增子序列,则rec[L+1] = k
若之前生成过长度为L+1的递增子序列,则比较k于rec[L+1]的大小;若k < rec[L+1], 令rec[L+1] = k;否则不进行任何操作。
参考代码:
<strong>class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
if (nums.empty())return 0;
vector<int> rec;
rec.push_back(1 << 31);
rec.push_back(nums[0]);
for (int i = 1;i < nums.size();++i){
int k = nums[i];
for (int j = 1;j < rec.size();++j){
if (rec[j-1] < k){
if (k < rec[j]){
rec[j] = k;
}
}else{
break;
}
}
if (k > rec[rec.size()-1]){
rec.push_back(k);
}
}
return rec.size() - 1;
}
};</strong>
优化:
以上的代码每次将rec数组从0到end-1判断一遍,求解lengthOfLIS的时间复杂度为O(n^2)。
是否能进一步优化呢?
由插入的规则可知,rec中的元素是递增的。
可以对rec数组进行二分查找,得到j的值, 每次二分查找的时间复杂度为O(log(n))。
求解lengthOfLIS的时间复杂度为O(nlog(n)).
需要注意,二分查找得到检查的位置后,需要判断k是否大于该位置的前一个元素,避免出现rec[L] = rec[L+1]的情况。
优化后的代码:
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
vector<int> rec;
rec.push_back(1 << 31);
for (int i = 0;i < nums.size();++i){
int k = nums[i];
auto p = upper_bound(rec.begin(),rec.end(),k);
auto f = p - 1;
if (*f < k){
if (p == rec.end())rec.push_back(k);
else *p = k;
}
}
return rec.size() - 1;
}
};