【LeetCode】300. Longest Increasing Subsequence

关键词:

最长递增子序列


问题描述:

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;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值