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

来源:互联网 发布:网络控制器没有驱动 编辑:程序博客网 时间:2024/06/08 14:44

题目

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