Leetcode 300. Longest Increasing Subsequences (nlogn复杂度)思路解析

题目

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.

Your algorithm should run in O(n2) complexity.

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

Credits:
Special thanks to @pbrother for adding this problem and creating all test cases.

思路解析

维护一份最大长度递增子序列对应的末尾元素为最小的状态数组,dp[len] = min(所有长度为len的子序列第len个元素)

暴力法: 2层循环,最外层每次迭代时,当前元素挨个与子序列比较,如果当前值与之前的dp数组对应的子序列构成了更长的序列,则更新。遍历的次数是(n-1)*n/2,时间复杂度为O(n^2)。

最优解:其实dp数组是单调递增,所以可以把内存循环的比较过程改成二分查找的方式,二分的时间复杂度为O(logn),所以优化后的时间复杂度是O(nlogn)

C++实现

暴力解:时间复杂度O(n^2), Runtime: 39 ms

class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        if (0 == nums.size()) return 0;
        int global_max = 0;
        vector<int> ret(nums.size());
        for (int i = 0; i < nums.size(); ++i) {
            ret[i] = 1;
            for (int j = 0; j < i; ++j) {
                if (nums[i] > nums[j]) {
                    ret[i] = max(ret[i], ret[j]+1);
                }
            }
            global_max = max(ret[i], global_max);
        }
        return global_max;
    }
};

最优解:时间复杂度O(nlogn), Runtime: 3 ms

class Solution {

// 找到第一个大于target的下标
private:
    int binaryFind(vector<int> dp, int target) {
        if (0 == dp.size()) return 0;
        int low = 0;
        int high = dp.size() - 1;
        if (dp[high] < target) return dp.size();
        while (low <= high) {
            int mid = (low+high)/2;
            // 注意这里需要等号,否则对于相同的连续值会算成多个,比如[2,2]会被误判成长度为2的递增子序列
            if (dp[mid] >= target) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }
        return low;
    }

public:
    int lengthOfLIS(vector<int>& nums) {
        if (0 == nums.size()) return 0;
        vector<int> dp;
        for (int i = 0; i < nums.size(); ++i) {
            int idx = binaryFind(dp, nums[i]);
            if (idx == dp.size()) dp.push_back(nums[i]);
            else dp[idx] = nums[i];
        }
        return dp.size();
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值