【leetcode】【medium】300. Longest Increasing Subsequence

230 篇文章 0 订阅

300. Longest Increasing Subsequence

Given an unsorted array of integers, find the length of longest increasing subsequence.

Example:

Input: [10,9,2,5,3,7,101,18]
Output: 4 
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. 

Note:

  • There may be more than one LIS combination, it is only necessary for you to return the length.
  • Your algorithm should run in O(n2) complexity.

Follow up: Could you improve it to O(n log n) time complexity?

题目链接:https://leetcode-cn.com/problems/longest-increasing-subsequence/

 

思路

法一:dp

存储空间用来记录长度为i串们的最后一个字符,其中最小的值。

class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        int len = nums.size();
        if(len<=1) return len;
        int rec[len+1];
        for(int i=0; i<=len; ++i){
            rec[i] = INT_MAX;
        }
        rec[1] = nums[0];
        int res = 1;
        for(int i=1; i<len; ++i){
            for(int j=1; j<len; ++j){
                if(rec[j]==nums[i]) break;
                else if(rec[j]>nums[i]){
                    rec[j] = nums[i];
                    res = max(res, j);
                    break;
                }
            }
        }
        if(nums[len-1]>rec[res]) ++res;
        return res;
    }
};

法二:dp+二分

可以看出,记录空间里的值是递增的,因此在记录空间查找时可以使用二分查找以加快运行速度。

总体思路和法1一样,加了一些优化。

class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        int len = nums.size();
        if(len<=1) return len;
        int rec[len+1], res = 1;
        for(int i=0; i<len; ++i){
            rec[i] = INT_MAX;
        }
        rec[1] = nums[0];
        for(int i=1; i<len; ++i){
            if(rec[res]<nums[i]){
                rec[++res] = nums[i];
            }else{
                int l = 1, r = res - 1;
                while(l<=r){
                    int mid = l + (r-l)/2;
                    if(rec[mid]<nums[i]){
                        l = mid+1;
                    }else {
                        r = mid-1;
                    }
                }
                rec[l] = nums[i];
            }
        }
        return res;
    }
};

思路来源:https://leetcode-cn.com/problems/longest-increasing-subsequence/solution/zui-chang-shang-sheng-zi-xu-lie-dong-tai-gui-hua-2/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值